Fundamentals of Python (learning notes)

Python Basics

1, Basic syntax and data types

indent

1. Indentation: the blank area before the beginning of a line of code to express the format framework of the program.
2.Python has mandatory requirements for indentation, which controls the structure and level of the program
3. Generally, 4 spaces or 1 TAB represent indentation
4. Indentation is divided into single-layer indentation and multi-layer indentation

notes

Single line note:

Start with #

#This is a single line comment expression

Multiline comment:

Three single quotes and three double quotes

'''
  What did you eat today
'''
"""
  Get ready for Teppanyaki
"""

Constant and Variable

difference

1. Stored value

Constant: a unit in memory used to store fixed values. In a program, the value of a constant cannot be changed;

Variable: it occupies a space in memory and is used to store the value (or address) of the variable. The stored value can be changed;

2. Naming conventions

Constant naming conventions: name constants and name variables are usually distinguished by all uppercase letters;

Variable naming specification: the first character must start with a uppercase or lowercase letter or underscore. It cannot start with a number or Chinese.
Module name: all lowercase letters without underscores.

Variable naming

Common variables: all lowercase letters, words are separated by underscores, such as my_var;
Global constant: all uppercase letters, words are separated by underscores, such as MY_CONST;
Class name: the first letter is capitalized, the words are directly connected together, and the hump naming method is adopted, such as MyClass

Identifiers and keywords

identifier

The identifier is the variable name, function name, class name, etc. defined by the programmer, which can clearly understand the specific meaning of the data stored in the variable

The identifier can be composed of letters, underscores and numbers, cannot start with a number, and cannot have the same name as the keyword

keyword

Keywords are identifiers that have been used inside Python and have special functions and meanings

The Python language has 33 reserved words

data type

1. Integer type

In Python 3, there is only one integer type, int, which has no size limit and can be used as a Long type.

There are four decimal representations of integers

Decimal: 1010, 99, - 217
Binary, starting with 0b or 0b: 0b010, -0B101 Byte
Octal, starting with 0o or 0o: 0o123, -0O456
Hex, starting with 0x or 0x: 0x9a, -0X89

The final output is in decimal

2. Floating point number

Floating point numbers can be represented by scientific counting

Use the letter E or E as the sign of power, base on 10, and the format is as follows:
a> E < B indicates a10b
For example, the value of 4.3e-3 is 0.0043 4.310-3
3.4e8 3.4108
9.6E5 value is 960000.0 9.6105

3. Boolean

Boolean values are represented by constants True and False
In a numeric context,

True is treated as 1 and False as 0

print(True+1)  #2

4. Plural

It is consistent with the concept of complex number in mathematics

z = 1.23e-4+5.6e+89j #1.23*10-4      5.6*1089

z.real get real part
z.imag obtains imaginary part

Both real and imaginary parts are floating point numbers

5. String

concept

String: an ordered sequence of characters consisting of 0 or more characters
A string is represented by a pair of single quotes or a pair of double quotes
A string is an ordered sequence of characters that can be indexed
"hello"----> h e l l o
Index ----- -- > 0 1 2 3 4

Escape character

1. Escape characters form some combinations to express some non printable meanings

Escape characterdescribe
\(at the end of the line)Continuation character
\\Backslash symbol
'Single quotation mark
"Double quotation mark
\bBackspace
\000empty
\nLine feed
\renter
String common operation conversion
'''
bin() Convert to binary and return a string
oct() Convert to octal and return a string
hex() Convert to hexadecimal and return a string
'''
a =bin(100)
print(a)
print(type(a))

b =oct(100)
print(b)
print(type(b))

c =hex(100)
print(c)
print(type(c))

'''
chr(x)Convert decimal to ASCLL Coded character
ord(x)hold ASCLL Convert coded characters to decimal
'''
print(chr(64))
print(ord("?"))


String case conversion

#Convert lower to lowercase
Str01 ="AGSSWGD"
print(Str01.lower())
#Convert upper to uppercase
Str02 ="hhvhjvvh"
print(Str02.upper())
#Split split
Str03 ="I,like,you"
Str04 =Str03.split(",")
print(Str04)
print(type(Str04))
#count calculation character
a =Str03.count(". ")
print(a)
#Center (width, character), single character
Str05 ="Is this melon cooked"
Str06 =Str05.center(30,"*")
print(Str06)
#strip removed characters
Str07 ="Zhang San Li Si Wang Wu"
Str08 =Str07.strip("Zhang San Wang Wu")
print(Str08)
#Join (character) links two characters
Str09 ="203721732723"
b =","
Str10 =b.join(Str09)
print(Str10)
#replace(old,new) replace the old substring with the new one
Str11 ="i,love,you"
Str12 =Str11.replace("you","Wu Yanhui")
print(Str12)
print(5/2)
format

First kind
The percentage sign is used to format the output. The usage is as follows:

%s. Represents a string;
%d. Represents an integer;
%f. Represents a floating point number.
%, representing a placeholder

name = "Zhang San"
age = 18
print("%s is %d year old"%(name,age))

be careful:
1. String and int cannot be spliced
2. Unknown data

Format: make the data more explicit. Lipstick 399 equipment 80 '
#The price of lipstick is 399
#The price of lipstick named commodity is 399

print("%s Name is%s yes%d"%("Price","commodity","Lipstick",399))

bug: placeholders must correspond to parameters one by one. Otherwise, the statement is not smooth and an error is reported

The second usage is as follows:

< template string >. Format (< comma separated parameters >)
Use {} as a placeholder
"{}'s lover is {}, and his son is {}"

print("{}My beloved is{},Er Tu is{}".format("Guo Degang","Luan Yunping","Guo Qilin"))

2, Data structure

1. list

The list is created with square brackets [] or list(), and the elements are separated by commas

Create list

list01 = [1,2,3,4,5,6]

Common functions

#Sum sum
print(sum(list01)) #21
#Statistics list element length len
print(len(list01)) #6
#max min Min
print(max(list01)) #6
print(min(list01)) #1

1.1 add

  1. list.insert(index, value) inserts data according to the subscript
  2. List. Append (value) is inserted at the end
  3. list.extend() adds the supernatural sequence elements to the list in turn
list01.insert(2,9)
print(list01) #[1, 2, 9, 3, 4, 5, 6]
list01.append("abc")
print(list01) #[1, 2, 9, 3, 4, 5, 6, 10]
list01.extend([7,8])
print(list01)

1.2 deletion

  1. list.pop(index) deletes the data at the specified location
  2. List. Remove (value) deletes the value, but it deletes the position where the value first appears
  3. list.clear() deletes all data
list01.pop(2)
print(list01)
list01.remove("abc")
print(list01)

1.3 modification

list[index] = value

list01[5] = "hhh"
print(list01)

1.4 query

  1. Query all -- print list names directly
  2. Query a single value using [index]
  3. Query multiple values [start:stop] left open and right closed decimals increase in the front and decrease in the reverse by one negative and one positive
    -6 -5 -4 -3 -2 -1
    [1, 2, 3, 4, 5, 'hhh']
    0 1 2 3 4 5
print(list01) #[1, 2, 3, 4, 5, 'hhh']
print(list01[4]) #5
print(list01[0:3]) #[1, 2, 3]
print(list01[-6:-3]) #[1, 2, 3]
print(list01[-6:3]) #[1, 2, 3]

common method

  1. list.reverse() reverses the list elements
  2. list.copy() copies list elements
  3. list.sort(reverse = Ture/False) sort is ascending by default reverse = Ture descending reverse = False ascending
  4. list.count() returns the number of occurrences of the element
list02 = [2,-2,4,5,7,-1,-5,9]
list02.reverse()
print(list02) #[9, -5, -1, 7, 5, 4, -2, 2]
list03 = list02.copy()
print((list03)) #[9, -5, -1, 7, 5, 4, -2, 2]
list02.sort()
print(list02) #[-5, -2, -1, 2, 4, 5, 7, 9]
list02.sort(reverse=True)
print(list02) #[9, 7, 5, 4, 2, -1, -2, -5]
list02.count(5)
print(list02)

2. tuple

tuple is a sequence type. Once created, it cannot be modified, added, deleted or modified

Create tuple

Created using parentheses () or tuple(), elements are separated by commas

#establish
tuple01 = (1,3,5,7,9)
tuple02 = tuple() #Empty tuple ()
tuple03 = tuple((2,4,6,8,10))
tuple04 = tuple01 + tuple03 #connect
print(tuple01)
print(tuple02)
print(tuple03)
print(tuple04) #(1, 3, 5, 7, 9, 2, 4, 6, 8, 10)

2.1 query

  1. Query all values and print tuple names directly
  2. Query single value [index]
  3. Query multiple values [start:stop] open left and close right, one negative and one positive
print(tuple01[3]) #7
print(tuple03[1:4]) #(4, 6, 8)
print(tuple03[-4:-1]) #(4, 6, 8)
print(tuple03[-4:4]) #(4, 6, 8)

3. Dictionary dict

Key value pair: a key is an extension of a data index. The [key:value] dictionary is a collection of key value pairs. Key value pairs are unordered (no index). Use < font color = "red"

Braces {} and dict() are created, and key value pairs are colon: it indicates that the dictionary type is the embodiment of "mapping" < dictionary variable > = {< key 1 >: < value 1 >,..., < key n >: < value n >}

Create dictionary

dict01 = {"Zhang San":18,"Li Si":20,"Wang Wu":40}
dict02 = dict() #Empty dictionary
dict03 = dict({"Zhao Liu":30,"Wu Qi":15,"Qian Ba":55})
print(dict01)
print(dict02)
print(dict03)

3.1 addition

  1. dict01 [new key] = add data with new value
  2. setdefault() is similar to get. If the key does not exist in the dictionary, the key will be added and the value will be set to default=None
dict01["Zhou Jiu"] = 25
print(dict01) #{'Zhang San': 18, 'Li Si': 20, 'Wang Wu': 40, 'Zhou Jiu': 25}
dict01.setdefault("ha-ha",77)
print(dict01)

3.2 deletion

  1. dict.pop(key) deletes a pair of data according to the key
  2. dict.clear() clears all data
dict01.pop("Li Si")
print(dict01) #{'Zhang San': 18, 'Wang Wu': 40, 'Zhou Jiu': 25}

3.3 modification

You can only modify the value, not the key
Because key s are unique and cannot be repeated, they cannot be modified to avoid duplication
First get the value dict01 ["Sun CE"] according to the key, and then re assign the value

dict01["Zhou Jiu"] = 66
print(dict01) #{'Zhang San': 18, 'Wang Wu': 40, 'Zhou Jiu': 66}

3.4 query

  1. dict.keys() view all keys (names)
  2. dict.values() queries all values (ages)
print(dict01.keys()) #dict_keys(['Zhang San', 'Wang Wu', 'Zhou Jiu'])
print(dict01.values()) #dict_values([18, 40, 66])

Query single value
1.dict[key] use key to query value
2.dict.get(key, default value) use the key to query the value. If there is no key, the default value will be output

print(dict03["Zhao Liu"]) #30
print(dict03.get("Zhao Liu")) #30
print(dict03.get("army officer's hat ornaments","No such person")) #No such person

Query all values (including key and value)
1. Print dictionary name directly
2.dict.items() iterative method

print(dict03) #{'Zhao Liu': 30, 'Wu Qi': 15, 'Qian Ba': 55}
print(dict03.items()) #dict_items([('Zhao Liu', 30), (Wu Qi ', 15), (Qian Ba', 55)])

common method

1. copy() copy
2. fromkeys() Create a new dictionary and return the corresponding initial value
3. items() Returns a list of all key value pairs and tuples
4. keys() Returns an all keys key List of components
5. values() Returns a list of all key value pairs
6. update() To update multiple key value pairs at a time
7. popitem() Randomly returns and deletes the last pair of key value pairs in the dictionary
8. k in dict  key Output in dictionary or not True ,Not in output False
#copy
dict04 = dict01.copy()
print(dict04) #{'Zhang San': 18, 'Wang Wu': 40, 'Zhou Jiu': 66}
old = ("Hu Ge","Wu Yanzu","Peng Yuyan")
#Create a new dictionary
new = dict.fromkeys(old,45)
print("The new dictionary is:%s"% str(new)) #The new dictionary is: {'Hu Ge': 45, 'Wu Yanzu': 45, 'Peng Yuyan': 45}
a ={'a':1,'b':2,'c':3,'d':4}
#Return key value pair
print(a.items()) #dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
#Return all key s
print(a.keys()) #dict_keys(['a', 'b', 'c', 'd'])
#Return all values
print(a.values()) #dict_values([1, 2, 3, 4])
#Update update value
b = {"e":5,"f":6,"g":7}
a.update(b)
print(a) #{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7}
#Returns the last key value pair
print(a.popitem()) #('g', 7)
print(a) #{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
#Determine whether it is in the dictionary class
print("e" in a) #True

4. set

A set is an unordered (no subscript) combination of multiple elements. The set type is consistent with the set concept in mathematics. The set elements are unordered, each element is unique, and there are no same elements
Collection elements cannot be changed and cannot be unique for variable data types

Create collection

Collections are represented by braces {} and elements are separated by commas
Create a collection type with {} or set()
To create an empty collection type, you must use set()

#establish
set01 = {1,2,3,4,5,6}
set02 = set() #Empty set
set03 = set({7,8,9,10})
print(set01)
print(set02) #set()
print(set03) #{8, 9, 10, 7} disorder

Empty set()

Empty list []
Empty tuple ()
Empty dictionary {}
The reason for the empty set() is that the dictionary creation is also {}, and the two conflict

print(type({})) #<class 'dict'>
print(type(set())) #<class 'set'>

4.1 add

  1. set.add() can also add existing data by adding one data. Although no error is reported, it is not displayed
  2. set01.update(set02) add data in batch and add set02 to set01
set01.add(-1)
print(set01) #{1, 2, 3, 4, 5, 6, -1}
set01.add(1)
print(set01) #{1, 2, 3, 4, 5, 6, -1}
#
set04 = {"qq","wechat","dy","game"}
set03.update(set04)
print(set03) #{7, 8, 9, 10, 'dy', 'qq', 'wechat', 'game'}

4.2 deletion

  1. Set.discard (value) deletes the value in the set. If the data does not exist, no error will be reported
  2. Set.remove (value) deletes the value in the set. If there is no value, an error KeyError exception will be reported
  3. set.pop() is deleted randomly. If it is an empty set, an error KeyError exception is reported
  4. set.clear() clear the set
set05 = {"Zhao","money","Sun","Lee","week","Wu","Zheng","king"}
set05.discard("money")
print(set05) #{'Wu', 'Zheng', 'Zhou', 'sun', 'Li', 'Zhao', 'Wang'}
set05.remove("king")
print(set05) #{'Wu', 'Zheng', 'Zhou', 'sun', 'Li', 'Zhao'}
set05.pop()
print(set05) #{'Zheng', 'Zhou', 'sun', 'Li', 'Zhao'}

4.3 modification

The collection is unique and cannot be changed

4.4 query

Print the set name directly. You can't use the index to query, because our set is out of order

print(set05) #{'Zhao', 'Zhou', 'Wu', 'sun', 'Zheng'}

Conversion method

set(x) converts other data types (x) to set types

Str = "hello"
print(Str) #hello
print(type(Str)) #<class 'str'>

b = set(Str)
print(type(b)) #<class 'set'>
print(b) #{'e', 'l', 'o', 'h'} random

Basic operations of sets

The union symbol is |, which returns all the values of the two sets union()

A,B = {1,3,2,4,5,7,8,0,6},{0,2,4,6}
print(A | B) #{0, 1, 2, 3, 4, 5, 6, 7, 8}
print(A.union(B)) #{0, 1, 2, 3, 4, 5, 6, 7, 8}

The sign of the difference set is - set01 - set02. Set01 removes the value of the common part
set01.difference(set02)

print(A - B) #{1, 3, 5, 7, 8}
print(A.difference(B)) #{1, 3, 5, 7, 8}

Symbol of intersection & the common part of two set01.intersection_update(set02) /intersection()

print(A & B) #{2, 4}
print(A.intersection_update(B)) #{2, 4}

Complement
1. Sign ^ symmetric difference set of complement
2. Union intersection = complement set01.symmetric_differwnce(set02)
3. Apart from the public part, I want the separate parts of set01 and set02

print(A ^ B) #{0, 1, 3, 5, 6, 7, 8}
print(A.symmetric_difference(B)) #{0, 1, 3, 5, 6, 7, 8}

Inclusion relation of collection

If the elements of set A are the elements of another set B, then A is A subset of B. If A is different from B, then A is called A true subset of B to determine whether it is A subset<=
set02.issubset(set01) uses the "> =" operator
set01.issuperset(set02) method to verify whether a set contains another set: the true subset can be judged by the symbol "<" or ">"

print( B <= A) #True
print(B.issubset(A)) #True
#
print(A >= B) #False
print(A.issuperset(B)) #True
#
print(B < A) #True
print(A < A) #False

Enhancer

The enhancer prints out the same as the intersection, except that it updates the value of s and the value of t remains unchanged

  1. s |= t
  2. s -= t
  3. s &= t
  4. s ^= t
s,t = {1,2,3,4,5,6},{4,5,6,7,8,9}
print(s | t) #{1, 2, 3, 4, 5, 6, 7, 8, 9}
s |= t
print(s) #{1, 2, 3, 4, 5, 6, 7, 8, 9}
print(t) #{4, 5, 6, 7, 8, 9}

Little practice

#Create an empty list
list01 = list()
print(list01)
#Add 5 elements
list01 =["Kobe","James","Duncan ","Yao Ming","Irving"]
print(list01)
#Modify the second element to Durant
list01[1] ="Durant"
print(list01)
#Add an element Jordan in the second position
list01.insert(1,"Jordan")
print(list01)
#Delete the first occurrence of the element
list01.remove("Kobe")
print(list01)
#Delete the element at position 3
list01.pop(3)
print(list01)
#Add the number 0 to the list
list01.append(0)
print(list01)
#Print index for 0
print(list01.index(0))
#Printout list length
print(len(list01))
#Maximum index element of printout list
list01 =["Kobe","James","Duncan ","Yao Ming","Irving"]
print(list01.index(max(list01)))
#clear list 
list01.clear()
print(list01)

#Create empty dictionary d
d ={}
print(d)
#Add 2 key value pair elements
d["a"]="1"
d["b"]="2"
print(d)
#Modify the second element 
d["b"]="3"
print(d)
#Determine whether "c" is the key of d
print("c" in d)
#Length of output d
print(len(d))
#Empty dictionary d
print(d.clear())


#Create collection
set01 ={1,2,3,4,5}
set02 ={2,5,8,4,1}
#Output set01 length
print(len(set01))
#Copy set02
set03 =set02.copy()
print(set03)
#Union
print(set01 | set02)
#intersection
print(set01 & set02)
#difference
print(set01 -set02)
#Complement
print(set01 ^ set02)
#s delete element 8
set02.discard(8)
print(set02)
#Add element 6
set02.add(6)
print(set02)
#Determine whether set02 is a subset of set01
print(set02.issubset(set01))

3, Built in and custom functions

Built in functions related to numbers


#abs calculation of absolute value
print(abs(-3))

divmod(x,y) (x//y) quotient and (x%y) remainder, while the output quotient and remainder x//y are divided and rounded down by x%y
Remainder = divisor divisor * quotient 10% - 3 = - 2

x = 10
y = 3


print(divmod(10,3)) #(3, 1)

pow(x,y) power X to the Y power --------- x ** y
pow(x,y,z) the result obtained by finding the Y power of X and Z for remainder - x**y%z

print(pow(x,y)) #1000
print(pow(x,y,3)) #1
print(pow(2,4,10)) #2**4 = 16  16%10=6

#round(x,f) round to decimal

print(round(3.1415926,4))#3.14

#max(x1,x2,...) returns the maximum value
#min(x1,x2,...) returns the minimum value

print(max(1,2,5,7,4,67))#67
print(min(1,2,5,7,4,67))#1

Sequence related built-in functions

All (sequence) all() accepts a sequence [] () {} set() all are false

a =["hello",3.14,4+3j,{"Zhang San":18,"Li Si":22}]
print(all(a))
b =["hello",3.14,4+3j,{"Zhang San":18,"Li Si":22},[]]
print(all(b))

c=[{}]
print(all(c))

any(x) returns True if it is True, otherwise it is False

d =[{},(),set()]
print(any(d))#False

range(start,stop,step) returns an iteration object
Left open right closed iterative object (list conversion is required to output)
Start: start value
stop: end value
Step: the step length is different from the interval

1. Omit the start value, and the start value will be 0 by default
2. The end value cannot be omitted
3. The step size can be omitted. If the step size is not written, it is 1 by default
The step size is 2 and the interval is 1
The step size is 3 and the interval is 2

a = range(10)
print(a) #range(0, 10)
print(list(a)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

c = range(1,10,2)
print(list(c)) #[1, 3, 5, 7, 9]
d = range(1,10,3)
print(list(d)) #[1, 4, 7]

sorted(x) returns a list in ascending order
reversed(x) reverse sort return iterator

a =[1,2,3,4,5,6]
print(sorted(a))#[1, 2, 3, 4, 5, 6]
#reversed(x) reverse sort
print(list(reversed(a)))#[6, 5, 4, 3, 2, 1]
c = [1,2,3,4,5,6]
print(reversed(c)) #<list_reverseiterator object at 0x0000026D0B74C7C8>

enumerate(x) iterates the sequence number and value:
Returns an iteration object and outputs the sequence number (subscript) and value

b =[1,3,6,4,8,0,2,9]
print(list(enumerate(b)))
#[(0, 1), (1, 3), (2, 6), (3, 4), (4, 8), (5, 0), (6, 2), (7, 9)]

slice(start,stop,step) slice, return a slice object start: start value stop: end value step: step
1. The step size can be omitted. The default value is 1

a = slice(5,15)
print(a) #slice(5, 15, None)
#Replace a with an iteration object
b = range(20)[a]
print(b) #range(5, 15)
print(list(b)) #[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Type dependent built-in functions

int(x) converts x to an integer, discards the decimal part, converts the string to an integer, and the numeric string can
print(int("wyh")) must be a numeric string

print(int(3.14)) #3
print("123") #123

float(x) converts x to decimal. Increasing the decimal part can change the string into decimal. It must be a numeric string
print(float("wyh"))

print(float(19))#19.0
print(float("20"))#20.0

complex(x) turns x into a complex number, adding the imaginary part to a string of numeric types

print(complex(20))#(20+0j)
print(complex(20.9))#(20+0j)
print(complex("20.9"))#(20+0j)

Isinstance (variable, type) type judgment,
If the variable and type are consistent and true,
Inconsistency is false
Type: STR int float list stub dict set

a = [1,2,3,4]
print(isinstance(a,list)) #True
print(isinstance(a,int)) #False

Custom function

definition

·Use the keyword def to guide;
·def is followed by the name of the function, and the parameters of the function are in parentheses. Different parameters are separated by commas "," and the parameters can be empty, but the parentheses cannot be omitted;
·The code block of the function should be indented;
·Use a pair of strings contained in "" as the description of the function to explain the purpose of the function. It can be omitted and will be displayed when viewing the function help;
·Use the keyword return to return a specific value. If omitted, return None.

def function name (parameter 1, parameter 2):

  • Code block

  • return

call
 def add(x,y):
	sum01 = x+y
	return sum01
print(add(2,3))#5

1. Parameters

Parameters can be 0 or multiple
Parameters with default values

call
  1. You can only pass one parameter, which is x, and y is the default value of 20
  2. If two parameters are passed in, the default value has no effect
def jia(x,y=20):
    a=x+y
    return a
print(jia(6,3))#9

2. Indefinite number of parameters

definition
  1. *The number indicates that this parameter is an uncertain number of parameters
  2. Multiple parameters need to be output circularly with for
  3. Accumulate in the for loop
def add(x,*y):
	total = x
	for i in y: 

accumulation

def add(x,*y):
    total =x
    for i in y:
        total += i
    return total
print(add(1,2,3,4,5,6,7,8,9))#45
print(add(1,2))#3
Return value

Can the return value be only one? Can it be multiple
Multiple values can be returned, separated by commas

Define call

 def suanfa(x,y):
    sum01 =x+y
    cheng01 =x*y
    chu01 =x/y
    return sum01,cheng01,chu01
print(suanfa(10,5))#(15, 50, 2.0)

Keywords: Python list

Added by dawnrae on Thu, 25 Nov 2021 21:52:34 +0200