# Python Basics

Posted by Horizon88 on Mon, 14 Feb 2022 16:44:37 +0100

## 1. Chain assignment

x=y=123  #Equivalent to x=123;y=123


## 2. Series unpacking assignment

a,b,c=4,5,6  #Equivalent to a=4;b=5;c=6


Using series unpacking assignment to realize variable exchange

a,b=1,2
a,b=b,a  #a. The values of b are interchangeable
print(a,b)


result:

a=2；b=1


## 3. Constant

python does not support constants. The value of each object can be changed

## 4. Data type

1. integer
2. float
3. Boolean type
4. String type

## 5. Digital operation symbols

python supports integers and floating-point numbers, and can operate on numbers

operatorexplainExamplesresult
-subtraction30-525
*multiplication3*618
/Floating point division8/24.0
//Integer division7//23
%Module (remainder)7%43
**power2**38

Note: 1 If the divisor is 0, an exception will be generated.
2. Quotient and remainder can be obtained simultaneously by using divmod() function.

divmod(13,3)  #A tuple is returned
#The result is (4,1)


## 6. Integer

In Python, in addition to decimal, there are three other decimal

• 0b or 0b, binary 0 # 1
• 0o or 0o, octal 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7
• 0x or 0x, hex 0 # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # a # b # c # d # e # f
>>>12
12
>>>0b101  #0b stands for binary and 101 is the number under binary
5
>>>0o10  #0o stands for octal, and 10 is the number under octal
8


Type conversion using int():

1. Floating point numbers directly discard the decimal part. If int(9.9), the result is 9
2. Boolean values True to 1 and False to 0. If int(True), the result is: 1
3. If the string conforms to the integer format (floating-point format cannot be used), convert it to the corresponding integer, otherwise an error will be reported
>>>int("456")  #String integer conversion
456
>>>int("456abc")
Result error


Automatic transformation:
Mixed operation of integer and floating point number, and the result is automatically transformed into floating point number

>>>2+8.0
10.0


## 7. Floating point number

Floating point number, called float
Floating point numbers are represented by scientific counting. For example, 3.14 is expressed as 314E-2

Type conversion and rounding

1. float can also convert other types to floating point numbers
2. round(value) returns a rounded value. Note: however, the original value will not be changed, but a new value will be generated
>>>round(3.14)
3


Enhanced assignment operator

operatorexampleequivalence
+=a+=2a=a+2
-=a-=2a=a-2
*=a*=2a=a*2
/=a/=2a=a/2
//=a//=2a=a//2
**=a**=2a=a**2
%=a%=2a=a%2

Note: "+ =" no space is allowed in the middle!

## 8. [operation] define multipoint coordinates_ Draw polylines_ And calculate the distance between the starting point and the midpoint

import turtle
import math
#Define coordinates
x1,y1 = 100,100
x2,y2 = 100,-100
x3,y3 = -100,-100
x4,y4 = -100,100
#Draw image
turtle.penup()
turtle.goto(x1,y1)
turtle.pendown()
turtle.goto(x2,y2)
turtle.goto(x3,y3)
turtle.goto(x4,y4)
#Calculate distance
distance = math.sqrt((x1-x4)**2+(y1-y4)**2)
turtle.write(distance)


Operation results:

## 9. Boolean value

0 stands for False and 1 for True

Comparison operator
Suppose variable a is 15 and b is 30

operatordescribeexample
==Equal - whether the values of the comparison object are equal(a = b) returns False
!=Not equal - compares whether the values of two objects are not equal(a! = b) return true
>Greater than - Returns whether x is greater than y(a > b) returns False
<Less than - Returns whether x is less than y(a < b) returns true
>=Greater than or equal - Returns whether x is greater than or equal to y(a > = b) return False
<=Less than or equal to - Returns whether x is less than or equal to(a < = b) return true

Logical operator

operatorformatexplain
Or (logical or)x or yIf x is true, y will not be calculated and true will be returned directly; If x is false, y is returned
And (logical and)x and yIf x is true, the value of Y is returned; If x is false, y is not calculated and false is returned directly
not (logical non)not xx is true and returns false; x is false and returns true

Same operator
The same operator is used to compare the storage units of two objects. The actual comparison is the address of the object.

operatordescribe
isIs is to judge whether two identifiers refer to the same object
is notis not determines whether two identifiers refer to different objects

Difference between is and = =:
Is is used to determine whether two variable reference objects are the same, that is, the address of the comparison object.
==Used to judge whether the values of variable reference objects are the same.

## 10. String

Encoding of string
Python 3 directly supports Unicode, which is 16 bit Unicode by default

Create string using quotation marks
You can create strings with single and double quotation marks. Use double quotation marks when a sentence contains single quotation marks, and single quotation marks when a sentence contains double quotation marks

a = "I'm a teacher"  #The sentence contains single quotation marks
b = 'my name is "TOM"'  #The sentence contains double quotation marks


You can create multiline text by three consecutive single or double quotation marks.

resume = ''' name="gaoqi"
company="sxt" age=18
lover="Tom" '''


The result is:

' name="gaoqi"\ncompany="sxt" age=18\nlover="Tom" '  #\n is an escape character, representing carriage return


Empty string and len() function
Python allows the existence of empty strings, which do not contain any characters and have a length of 0. For example:

>>>c = ''
>>>len(c)
0


len() is used to calculate how many characters a string contains. For example:

>>>d = 'abc Shang Xuetang'
>>>len(d)
6


Escape character

Escape characterdescribe
(at the end of the line)Continuation character
\\Backslash symbol
\'Single quotation mark
\"Double quotation mark
\bBackspace
\nLine feed
\thorizontal tab
\renter
>>> a = 'I\nlove\nU'
>>> a
'I\nlove\nU'
>>> print(a)
I
love
U
>>> print('aaabb\
cccddd')
aaabbcccddd


String splicing

• You can use + to splice multiple strings
(1) If both sides of + are strings, then splicing.
(2) If both sides of + are numbers, it is an addition operation.
(3) If the types of + are different, an exception is thrown.
• Multiple literal strings can be put together to achieve splicing
>>> a = 'sxt'+'gaoqi'
>>> a
'sxtgaoqi'
>>> b = 'sxt''gaoqi'
>>> b
'sxtgao


String copy
You can use * to assign a string

>>> a = 'Sxt'*3
>>> a
'SxtSxtSxt'


Non wrapping printing
When we called print earlier, a new line character will be printed automatically. Sometimes we don't want to add line breaks. Sometimes we don't want to add line breaks. We can add anything at the end by ourselves through the parameter end = "any string"

print("sxt",end=' ')
print("sxt",end='##')
print("sxt")


Operation results:

sxt sxt##sxt


Read string from console
You can use input() to read the contents entered by the keyboard

>>> myname = input("Please enter your name:")
>>> myname
'Gao Qi'


str() implements digital transformation string
str() can convert other data types to strings

str(5.20)  # '5.20'
str(3.14e2)  # '314.0'
str(True)  # 'True'


Extract characters using []

>>> a = 'abcdefghijklmnopqrstuvwxyz'
>>> a[0]
'a'
>>> a[3]
'd'
>>> a[26-1]
'z'
>>> a[-1]
'z'
>>> a[-26]
'a'
>>> a[-30]
Traceback (most recent call last):
File "<pyshell#91>", line 1, in <module>
a[-30]
IndexError: string index out of rang


replace() implements string replacement
The string is "immutable". We can get the characters at the specified position of the string through [], but we can't change the string

>>> a = 'abcdefghijklmnopqrstuvwxyz'
>>> a[3]='high'
Traceback (most recent call last):
File "<pyshell#94 > ", line 1, in < module > a [3] = 'high' TypeError: 'str' object does not support item assignment


The string cannot be changed. However, we do sometimes need to replace certain characters. At this point, you can only do this by creating a new string

>>> a = 'abcdefghijklmnopqrstuvwxyz'
>>> a = a.replace('c','high')
'ab high defghijklmnopqrstuvwxyz'


In the whole process, instead of modifying the previous string, we actually created a new string object and pointed to variable a. The memory diagram is as follows

String slice operation
Slicing slice allows us to quickly extract substrings. The standard format is: [start offset: end offset: step]

Operation and descriptionExamplesresult
[:] extract the entire string"abcdef"[:]"abcdef"
[start:] from start to end of index"abcdef"[2:]"cdef"
[: end] know end-1 from the beginning"abcdef"[:2]"ab"
[start: end] from start to end-1"abcdef"[2:4]"cd"
[start: end: step] extract from start to end-1, and the step is step"abcdef"[1:5:2]"bd"

Other operations (three quantities are negative):

Examplesexplainresult
"abcdefghijklmnopqrstuvwxyz"[-3:]The last three"xyz"
"abcdefghijklmnopqrstuvwxyz"[-8:-3]From the last eight to the last three (Baotou but not Baowei)'stuvw'
"abcdefghijklmnopqrstuvwxyz"[::-1]The step size is negative, and the extraction is reversed from right to left'zyxwvutsrqponmlkjihgfedcba'

When slicing, the start offset and end offset are not in the range of [0, string length - 1], and no error will be reported. If the start offset is less than 0, it will be treated as 0, and if the end offset is greater than "length - 1", it will be treated as - 1. For example:

>>>a= "abcdefg"
>>>a[3:50]
'defg'


split() split and join() merge
split() can separate a string into multiple substrings (stored in a list) based on the specified separator. If no delimiter is specified, white space characters (newline / space / tab) are used by default.

>>> a = "to be or not to be"
>>> a.split()
['to', 'be', 'or', 'not', 'to', 'be']
>>> a.split('be')
['to', 'or not to', '']


The function of join() is just the opposite of that of split(), which is used to connect a series of substrings.

>>> a = ['sxt','sxt100','sxt200']
>>> '*'.join(a)
'sxt*sxt100*sxt200'


Key points of string splicing: using string splicer + will generate new string objects, so + is not recommended to splice strings. It is recommended to use the join function, because the join function will calculate the length of all strings before splicing strings, then copy them one by one, and create objects only once.

String resident mechanism and string comparison
String resident: a string that conforms to the identifier rule * (only contains underscores () Letters and numbers) * enables string persistence.

>>> a = "abd_33"
>>> b = "abd_33"
>>> a is b
True  #a. B compliance only includes underline () Rules for letters and numbers
>>> c = "dd#"
>>> d = "dd#"
>>> c is d
False  #c,d contain#, non-conforming, only including underscore () Rules for letters and numbers


String comparison and identity
Use = == A string is compared to a value
Using is / not is, the string is compared to the address

Member operator
in /not in keyword to judge whether a character (substring) exists in the string

Summary of common methods of string
I'm Gao Qi. I'm 18 years old. I work in Beijing shangxuetang science and technology. My son's name is goloshi. He's six years old. I am a popularizer of programming education and hope to influence 60 million Chinese who learn programming. My son is also learning programming now. I hope he can surpass me when he is 18

Methods and usage examplesexplainresult
len(a)String length96
a. Startswitch ('I'm Gao Qi ')Starts with the specified stringTrue
a. Endswitch ('pass me ')Ends with the specified stringTrue
a.find('high ')The first occurrence of the specified string2
a.rfind('high ')The last occurrence of the specified string29
a.count("programming")The specified string appears several times3
a.isalnum()All characters are letters or numbersFalse

Remove header and tail information
strip() is used to remove the specified information at the beginning and end of the string (not in the middle). lstrip() removes the specified information on the left side of the string, and rstrip() removes the specified information on the right side of the string

>>> "*s*x*t*".strip("*")
's*x*t'
>>> "*s*x*t*".lstrip("*")
's*x*t*'
>>> "*s*x*t*".rstrip("*")
'*s*x*t'
>>> " sxt ".strip()
'sxt'


toggle case
a = "gaoqi love programming, love SXT"

Examplesexplainresult
a.capitalize()Capitalize the string to produce a new initial'Gaoqi love programming,love sxt'
a.title()Generates a new string with each word capitalized'Gaoqi Love Programming, Love Sxt'
a.upper()Generate a new string and convert all characters to uppercase'GAOQI LOVE PROGRAMMING, LOVE SXT'
a.lower()A new string is generated, and all characters are converted to lowercase'gaoqi love programming, love sxt'

Typesetting
The three functions center(), ljust(), and rjust() are used to typeset strings.

>>> a="SXT"
>>> a.center(10,"*")  #10 characters are required, centered and filled with * sign
'***SXT****'
>>> a.center(10)  #10 characters are required, aligned in the center and filled with spaces by default
' SXT '
>>> a.ljust(10,"*")  #Need 10 characters, left justified, filled with * sign
'SXT*******'


Other methods

1. Is isalnum() alphabetic or numeric
2. isalpha() detects whether the string is only composed of letters (including Chinese characters)
3. isdigit() detects whether a string consists only of numbers
4. isspace() detects whether it is a blank character
5. Is isupper() uppercase
6. Is islower() lowercase
>>> "sxt100".isalnum()
True
>>> "sxt Shang Xuetang".isalpha()
True
>>> "234.3".isdigit()  #Because there is a decimal point, it is false
False
>>> "23423".isdigit()
True
>>> "aB".isupper()
False
>>> "A".isupper()
True
>>> "\t\n".isspace()
True


String formatting

• Basic usage of format()
Python2. Starting from 6, a new function str.format() for formatting strings is added, which enhances the function of string formatting
The basic syntax is to replace the previous% by {} and:
The format function can accept unlimited parameters, and the positions can be out of order
>>> a = "The name is:{0},Age:{1}"
>>> a.format("Gao Qi",18)
'The name is:Gao Qi,Age: 18'
>>> a.format("Gao Xixi",6)
'The name is:Gao Xixi,Age: 6'

>>> b = "The name is:{0}，Age is{1}. {0}He's a good guy"
>>> b.format("Gao Qi",18)
'Name is: Gao Qi, age is 18. Gao Qi is a good guy'

>>> c = "The name is{name}，Age is{age}"
>>> c.format(age=19,name='Gao Qi')
'His name is Gao Qi and his age is 19'

• Fill and align
Padding is often used with alignment
^, <, > are centered, left aligned and right aligned respectively, followed by width
: the filled character after the sign can only be one character. If it is not specified, it is filled in with a space by default
>>> "{:*>8}".format("245")
'*****245'
>>> "I am{0},I like numbers{1:*^8}".format("Gao Qi","666")
'I'm Gao Qi,I like numbers**666***'

• Number formatting
Floating point numbers are formatted through f and integers through d
>>> a = "I am{0}，My deposit has{1:.2f}"
>>> a.format("Gao Qi",3888.234342)
'I'm Gao Qi. My deposit is 3888.23

• Other formats:
numberformatoutputdescribe
3.1415926{:.2f}3.14Keep two decimal places
3.1415926{:+.2f}3.14Two decimal places are reserved for the sign
2.71828{:.0f}3Without decimals
5{:0>2d}05Number zero padding (fill left, width 2)
5{:x<4d}5xxxDigit complement x (fill right, width 4)
10{:x<4d}10xxDigit complement x (fill right, width 4)
1000000{:,}1,000,000Comma separated number format
0.25{:.2%}25.00%Percentage format
1000000000{:.2e}1.00E+09Exponential notation
13{:10d}13Align right (default, width is 10)
13{:<10d}13Align left (width 10)
13{:^10d}13Middle alignment (width 10)

## 11. Practical operation

1. Use python to express the mathematical formula: 5 + 10 x 5 − 13 ( y − 1 ) ( a + b ) x + 9 ( 5 x + 12 + x y ) \frac{5+10x}{5}-\frac{13(y-1)(a+b)}{x}+9(\frac{5}{x}+\frac{12+x}{y}) 55+10x​−x13(y−1)(a+b)​+9(x5​+y12+x​)
>>> (5+10x)/5-13*(y-1)*(a+b)/x+9*(5/x+(12+x)/y)

1. Input the user's monthly salary from the console and calculate the annual salary. Print out the user's annual salary
>>> a=float(input("Monthly salary of users:"))
Monthly salary of users: 123
>>> a*12
1476.0

1. Use string copy, print out "love you a hundred times" with the computer, and print it 100 times
>>>a="Love you a hundred times"
>>>a*100

1. Output "to be or not to be" strings in reverse order
>>>a="to be or not to be"
>>>a[::-1]

1. Output all s in the "sxtsxtsxtsxtsxt" string
>>> a="sxtsxtsxtsxtsxt"
>>> a[::3]

1. Judge the following output results and explain the reasons in words:
>>> a = "abd_33"
>>> b = "abd_33"
>>> c = "dd#"
>>> d = "dd#"
>>> a is b #output true or false?  ##True.  Because a and b match, only underscore () is included Rules for letters and numbers
>>> c is d #output true or false?  ##False. because c and d Contains#No., not just underscore () Letters and numbers

1. Write the following code to print the results:
>>> c = "The name is{name}，Age is{age}"
>>> c.format(age=19,name='Gao Qi')


Results: "the name is Gao Qi and the age is 19"

Topics: Python