[Python Tutorial] An Easy Introduction to Python

Introduction

This is an attempt to read the 3rd edition of the Python tutorial and make a note of what you have learned.

Python Tutorial 3rd Edition

And when I finish reading, I would like to take this exam By the time it's over, the test will start ...

Python 3 Engineer Certification Basic Exam

I hope it continues, I hope it continues

Use Python as a calculator

Numerical value

Number type

--Integers have ʻinttype --Numbers with decimals have afloattype --Division always returns thefloat` type

>>> 2 + 2
4
>>> 50 - 5 * 6
20
>>> (50 - 5 * 6) / 4
5.0
>>> 8 / 5
1.6
>>> 17 / 3
5.66666666666667

Four arithmetic operations

--Use the // operator if you want to perform devaluation division to get an integer solution (if you want to discard the remainder) --Use the % operator if you only want to get the remainder

>>> 17 // 3
5
>>> 17 % 5
2
>>> 5 * 3 + 2
17

--The power can be calculated by using the ** operator.

>>> 5 ** 2
25
>>> 2 ** 7
128

--If the types to be operated on are mixed, the integer is converted to a floating point number.

>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

variable

--The equal sign (=) is used to assign a value to a variable

>>> width = 20
>>> height = 5 * 9
>>> width * height
900

--An error occurs if you try to use a variable without "defining" (assigning a value).

#If you try to access an undefined variable, you will get a NameError because the variable is not defined.
>>> n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

--In interactive mode, the last displayed value is assigned to the variable " _ "(underscore).

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

Other numeric types

--Various numeric types are supported, such as decimal and rational numbers. --Complex numbers are also supported, using the suffix "j" or "J" to indicate their imaginary part (eg 3 + 5j).

String

Quotation marks

--You can use single quotes ('...') or double quotes ("...") for quotes, both with the same result. --You don't need to escape double quotes in single quotes
(single quotes need to be escaped like \') --No need to escape single quotes in double quotes --You can escape quote characters with a backslash (\) --Backslash is entered and displayed with a yen sign on Japanese keyboards and Japanese fonts

>>> 'spam eggs' #Single quote
'spam eggs'
>>> 'doesn\'t' #Single quote\To escape with...
"doesn't"
>>> "doesn't" # ...Use double quotes
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

--In the interpreter, strings are enclosed in quotes and special characters are output escaped with \. --The quotes in the display are double quoted only if the string itself contains single quotes and does not contain double quotes, otherwise it is single quoted.

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'
>>> s # print()If you display without\n is included in the output
'First line.\nSecond line.'
>>> print(s) # print()With\Line break occurs at n
First line.
Second line.

raw character

--Use ** raw string ** to prevent characters prefixed with "" from being interpreted as special characters

>>> print('C:\some\name') # \because n is a line break
C:\some
ame
>>> print(r'C:\some\name') #Note the r before the quotes
C:\some\name

Triple quotes

--You can also write string literals over multiple lines --Use triple quotes ("" "..." "" or'''...''') --Put \ at the end of the line to avoid automatically including end-of-line characters in the string

#If you do the following
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")

#You get the following output (note that the first newline is not included)
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to

String concatenation

--Strings can be concatenated with the + operator and repeated with the * operator

#Repeat un 3 times and add ium at the end
>>> 3 * 'un' + 'ium'
'unununium'

--Enumerated string literals (quoted) are automatically concatenated --Convenient when you want to split a long character string --Valid only between literals, not valid for variables and expressions

>>> 'Py' 'thon'
'Python'
>>> text = ('A long character string in parentheses'
'Let's put it in and connect it.')
>>> text
'Let's put a long character string in the parenthesis and connect it.'

--Use + to concatenate variables and literals, and concatenate variables

>>> prefix = 'Py'
>>> prefix + 'thon'
'Python'

index

--Character strings can be ** indexed ** (specified by serial number) --The first character is 0 ――The character here is a character string with a length of 1.

>>> word = 'Python'
>>> word[0] #Character at position 0
'P'
>>> word[5] #Character at position 5
'n'

--Negative numbers can be used for the index, indicating that counting from the right --- 0 is the same as 0, so negative indexes start at -1

>>> word = 'Python'
>>> word[-1] #Last character
'n'
>>> word[-2] #The penultimate character
'o'
>>> word[-6]
'P'

--An error will occur if you specify an index that is too large.

>>> word[42] #word is 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

Slicing

--While you can get individual characters by using index, you can get substrings by slicing.

>>> word = 'Python'
>>> word[0:2] #Characters from position 0 to 2 (including 0) (not including 2)
'Py'
>>> word[2:5] #Characters from position 2 to 5 (including 2) (not including 5)
'tho'

--Note that the start point is always included and the end point is always excluded --This ensures that s [: i] + s [i:] is always equivalent to s.

>>> word = 'Python'
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

--The default value for the first character is 0 --The default value for the second character is the size of the string

>>> word = 'Python'
>>> word[:2] #Characters from the first character to position 2 (not including 2)
'Py'
>>> word[4:] #Characters from position 4 (including 4) to the end
'on'
>>> word[-2:] #position-Characters from 2 (including) to the end
'on'

--How to remember slicing -** Index is a number that indicates the "between" characters ** -** The left end of the first character is 0 ** -** Index n is to the right of the last character in the n-character string ** -** Slicing from index i to j [i: j] consists of all characters between boundary i and boundary j ** -** For non-negative indexes, the slicing length is the difference between the two indexes (word [1: 3] length is 2) **

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

--In slicing, even if you specify an index outside the range, it will be processed in a good way.

>>> word = 'Python'
>>> word[4:42]
'on'
>>> word[42:]
''

Immutable

--Since Python strings cannot be modified, an error will occur if you assign to the index position of the string.

>>> word = 'Python'
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment

--If you need a different string, you need to generate a new one

>>> word = 'Python'
>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

list

Overview

--Python has several types for complex data that can be used to combine other types of values --The most versatile is the list, which puts comma-separated values (items) in the brackets. --Lists can contain items of different types, but usually all have the same type

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

Index and slicing

--Like strings (like all other sequence types), lists can use indexes and slicing

>>> squares = [1, 4, 9, 16, 25]
>>> squares[0] #Indexing returns an item
1
>>> squares[-1]
25
>>> squares[-3:] #Slicing creates and returns a new list
[9, 16, 25]

--Can be assigned to slicing --You can change the length of the list and clear all the contents of the list.

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> #Replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> #Delete these
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> #Clear the list. Replace all elements with an empty list
>>> letters[:] = []
>>> letters
[]

--Slicing operations always return a new list containing the requested elements ――The following slicing is a movement to make a new shallow copy and return it

>>> squares = [1, 4, 9, 16, 25]
>>> squares[:]
[1, 4, 9, 16, 25]

List concatenation

--Lists also support operations such as concatenation

>>> squares = [1, 4, 9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Mutable

--The string was immutable, but the list is ** mutable **, that is, the contents can be replaced.

>>> cubes = [1, 8, 27, 65, 125] #Something is wrong
>>> 4 ** 3 #The cube of 4 is 64. Not 65!
64
>>> cubes[3] = 64 #Swap the wrong values
>>> cubes
[1, 8, 27, 64, 125]

Add item

--Items can be added to the end of the list by using the ʻappend ()` method

>>> cubes = [1, 8, 27, 64, 125]
>>> cubes.append(216) #Added 6 to the 3rd power
>>> cubes.append(7 ** 3) #Add 7 to the 3rd power
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Nesting the list

--Lists can be nested

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

the term

literal

--The actual value of a numerical value or character string, such as a constant, is simply described.

Sequence type

--Composed of multiple elements, with the elements arranged in order (list, etc.)

Shallow copy

--A copy of a pointer that does not involve duplication of an object

Recommended Posts

[Python Tutorial] An Easy Introduction to Python
An introduction to Python Programming
An introduction to Python for non-engineers
An introduction to Python for machine learning
An introduction to Python for C programmers
Introduction to OpenCV (python)-(2)
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
[Python] Easy introduction to machine learning with python (SVM)
Introduction to Python "Re" 1 Building an execution environment
Introduction to Python Django (2) Win
An introduction to private TensorFlow
Introduction to serial communication [Python]
Introduction to Python (Python version APG4b)
An introduction to Bayesian optimization
An introduction to Python distributed parallel processing with Ray
Reading Note: An Introduction to Data Analysis with Python
[Introduction to Udemy Python 3 + Application] 58. Lambda
[Introduction to Udemy Python 3 + Application] 31. Comments
Easy way to customize Python import
Introduction to Python Numerical Library NumPy
An introduction to Mercurial for non-engineers
Practice! !! Introduction to Python (Type Hints)
[Introduction to Python3 Day 1] Programming and Python
[Introduction to Python] <numpy ndarray> [edit: 2020/02/22]
[Introduction to Udemy Python 3 + Application] 57. Decorator
Introduction to Python Hands On Part 1
[Introduction to Python3 Day 13] Chapter 7 Strings (7.1-7.1.1.1)
[Introduction to Python] How to parse JSON
[Introduction to Udemy Python 3 + Application] 56. Closure
[Introduction to Python3 Day 14] Chapter 7 Strings (7.1.1.1 to 7.1.1.4)
Python tutorial
Introduction to Protobuf-c (C language ⇔ Python)
[Introduction to Udemy Python3 + Application] 59. Generator
[Introduction to Python3 Day 15] Chapter 7 Strings (7.1.2-7.1.2.2)
[Introduction to Python] Let's use pandas
[Python] An easy way to visualize energy data interactively [plotly.express]
[Introduction to Python] Let's use pandas
[Introduction to Udemy Python 3 + Application] Summary
An introduction to Python that even monkeys can understand (Part 1)
Easy Python to learn while writing
Introduction to image analysis opencv python
[Introduction to Python] Let's use pandas
An introduction to Python that even monkeys can understand (Part 2)
Introduction to Python Django (2) Mac Edition
An alternative to `pause` in Python
[Introduction to Python3 Day 21] Chapter 10 System (10.1 to 10.5)
An easy way to hit the Amazon Product API in Python
[Introduction to Udemy Python3 + Application] 18. List methods
[Introduction to Udemy Python3 + Application] 63. Generator comprehension
[Introduction to Python] How to use class in Python?
[Introduction to mediapipe] It's really easy to move ♬
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
[Introduction to Udemy Python3 + Application] 33. if statement
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Udemy Python3 + Application] 13. Character method
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.1-8.2.5)
python3 How to install an external module
[Introduction to Udemy Python3 + Application] 55. In-function functions
[Introduction to Udemy Python3 + Application] 48. Function definition
How to convert Python to an exe file
[Introduction to Python3, Day 17] Chapter 8 Data Destinations (8.3-8.3.6.1)