Summary of basic knowledge of python (here comes the benefits for beginners)... Life is short. I use python

Summary of basic knowledge of Python... Life is short. I use python

preface

Python is an easy to learn and powerful programming language. It provides efficient high-level data structure and simple and effective object-oriented programming. Python's elegant syntax and dynamic typing, as well as the essence of interpretive language, make it an ideal language for scripting and rapid application development on most platforms.

Python interpreter and rich standard libraries provide source code or machine code applicable to various main system platforms, which can be found on the python official website https://www.python.org/ Free access and free distribution. Many free third-party Python modules, programs, tools and their documentation can also be found on this website.

The Python interpreter is easy to extend and can use C or C + + (or other languages that can be called through C) to extend new functions and data types. Python can also be used as an extender language in customizable software.

notes

Comments can make people who read the code know the function of the code more clearly, and comments can enhance the readability of the code
 Single-Line Comments , multiline comment ,
 stay Python inside # The number represents a single line note
 multiline comment 
"""
This is a hyperhidrosis note, Press and hold shift+"(Press three times")Multiple lines of comments can appear
"""

data type

  1. int numeric integer
  2. Float float type (decimal point)
  3. Bool boolean type (true (true, 1), false (false, 0))
  4. String string (all strings with quotation marks)
  5. List list
  6. Tuple Yuanzu
  7. Dictionary dictionary

Among the data types of Python 3:

Immutable data (3): Number, String, Tuple;
Variable data (3): List, Dictionary, Set.

Variable name

Variable name: it is composed of letters, numbers and underscores. The number cannot start. The variable name should be associated with the actual data (see the meaning of the name)
Keywords cannot be used for naming
Two nomenclature:
1. Big hump naming method: the first letter of each word is capitalized My_Name=
2. Small hump naming: except for the letter of the first word, the first letter of other words shall be capitalized my_Name_Is=

value type

integer

# Integer: integer
num_i_1 = 88    # i is the abbreviation of int (integer)
num_i_2 = 66
print(num_i_1)
print('Can you send me a message%d Red envelope?' % num_i_1)  # %Placeholder% d is decimal
print('Can you send me a message%o Red envelope?' % num_i_1)   # %o is octal
print('Can you send me a message%x Red envelope?' % num_i_1)   # %x is hexadecimal
print('Can you send me a message%d A red envelope? Or%d Red envelope' % (num_i_1, num_i_2))

Floating point number

# float floating point number
num_f_1 = 1.68888888
print(num_f_1)
print('Can you send me a message%f Red envelope?' % num_f_1)    # Format output floating-point number type, with 6 digits after the decimal point reserved by default
print('Can you send me a message%.3f Red envelope?' % num_f_1)  # A decimal point plus a number means that three digits after the decimal point are retained

Boolean type

True=1
type(True)
Output: class'bool'

False=0
type(False)
Output: class'bool'

Complex a+bi

complex_1 = complex(1, 2) # 1 is a and 2 is b

character string

# character string
str_1 = 'good morning'
str_2 = 'good afternoon'
str_3 = 'good night'
print('%s,Have you eaten yet?' % str_1)
print('{},Have you eaten yet?' .format(str_2))
print(f'{str_3},Have you eaten yet?')
print('{},{},Have you eaten yet?'.format(str_1, str_2))

replace

str_4 = 'play football'
print(str_4)
print(str_4.replace('football', 'basketball'))   # The replaced character is preceded by the replaced new character

strip remove

# Remove blank space at both ends (as a crawler for automatic processing Excel) strip (remove the horizontal tab \ n line feed)
str_5 = '\tplay football\n'
print(str_5)
print(str_5.strip())

Cut split

# Cut (do crawler, do automatic processing, Excel) split
str_6 = 'go to school'
list_7 = str_6.split('o')
print(list_7)
print(type(list_7))

Splice join

print('-'.join(str_6))
print('o'.join(list_7))

String case conversion

# String case conversion upper to uppercase lower to lowercase
str_8 = 'day day up'
print(str_8.upper())
print(str_8.lower())

Search and statistics

print(len(str_8))   # len() counts the length of data entered in parentheses
print(len('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@'))

count statistics

# count counts the number of occurrences of characters
print(str_8.count('a'))
print(str_8.count('d'))

Find find

# find finds whether the character returns the subscript of the first found letter in the string
print(str_8.find('u'))  # You can search by Region (if you don't give a region, you can search the whole string). If not, return - 1
print(str_8.index('y', 3, 8))   # You can find index by Region: similar to find. If it is not there, an error will be reported
# rfind: the same as find, but it starts from the right
print(str_8.rfind('u'))
print(str_8.rindex('y', 3, 8))

Judgment and detection

# judge
str_9 = '166529822545'
str_10 = 'adwfvhgcgajfkg'
print(str_9.isdigit())  # isdigit() judges that the data in brackets are all numbers
print(str_10.isalpha()) # isalpha() judges that the data in the brackets are all letters
# Detection type()
num_1 = 141651
print(type(num_1))
str_11 = '168'
print(type(str_11))
list_1 = [1, 6, 8]
print(type(list_1))
tuple_1 = (1, 6, 8)
print(type(tuple_1))
dict_1 = {'1': 1, '6': 6, '8': 8}
print(type(dict_1))
set_1 = {1, 6, 8}
print(type(set_1))

Forced transformation

num_f_1 = float(num_1)
print(num_1)
print(num_f_1)
str_12 = str(num_1)
print(num_1)
print(type(num_1))
print(str_12)
print(type(str_12))

operator

# operator

# Arithmetic operator 
 plus  +
 minus sign  -
 multiplication sign  *
 division  /
 Take integer  //
 Remainder  %
 power   **


# Comparison (relational) operator
 ==   Check whether the two parameters are equal , Conditional return True
 !=    Check whether the two parameters are not equal , Conditional return True
 > If the number on the left of the greater than sign is greater than the number on the right, it returns True
 < Less than sign
 >= Greater than or equal to
 <= Less than or equal to


 num_1 = int(input('Please enter a number:'))
 num_2 = int(input('Please enter a number:'))
 print(num_1 >= num_2)


# Logical operator
 and  And   x and y    x and y Return only when you are satisfied True, If one of them is not satisfied, return False
 or   perhaps   x or y   x and y There is a satisfaction, there is a satisfaction, Return if you are not satisfied False
 not  no    If x by True Just return False, If x by False Just return True


# Assignment Operators 
 stay Python in,use=Number can assign a value to a variable
 +=  c = c + b  Can be abbreviated as  c += b
 -=  c = c - b  Can be abbreviated as  c -=b
 *=  c = c + b  Can be abbreviated as  c *= b
 /=  c = c + b  Can be abbreviated as  c /= b
 //=c = c + b can be abbreviated as c //= b
 %=  c = c + b  Can be abbreviated as  c %= b
 **=  c = c + b  Can be abbreviated as  c **= b

 c = 0
 a = 1
 b = 2
 a = a + b
 a += b

# Operator precedence 
 **   Highest priority
  *  /  %   //
 + -
 <= <  > >=
 ==   !=
 =  %=  /=   //=  -=  +=  *=  **=
 not or and    Lowest priority


# Common data type conversion

a = int(input('Enter a number:'))
a = hex(a)
print(a)


c = 2
c = str(c)
c = float(c)
c = int(c)
print(c)

Judgment statement if

# Judgment statement, given a condition, if it is judged whether the condition is true during program execution, perform different operations according to the judgment results, so as to change the execution order of the code

 if Pay today:
     Pay back your credit card first
     if Have surplus:
         It's still a flower
     else:
         No money, Nothing can be done
 else:
     Waiting for salary

 Press and hold tab Keys can also be indented, One indent equals four spaces, tab Do not mix with spaces
 if (Conditions to judge):
     Conditions established,Just execute

 age = int(input('Please enter your age:'))
 Judge whether the age is greater than or equal to 18 years old
 if age >= 18:
     print('You can enter the Internet cafe Hi, PI')
 else:
     print('No adult,You can't go to the Internet bar to surf the Internet')

 else When the processing conditions are not met

Nested use of if

# Nested use of if
# if nested application scenarios, add additional judgment on the premise that the previous conditions are met
 if Condition 1:
     Code executed when condition 1 is met
     if Add condition 2 to the satisfaction of condition 1:
         When condition 2 is met,Executed code

     else:
         Condition 2 does not satisfy the executed code
 else:
     Code executed when condition 1 is not met

Advanced level of if statement

# For the advanced elif of if statement, the conditions are different, and the code to be executed is also different. Elif is used for multi-level conditional judgment

 if Condition 1:
     Code executed when condition 1 is met

 elif Condition 2:
     Code executed when condition 2 is met

 elif Condition 3:
     Code executed when condition 3 is met

 else:
     Code executed when none of the above conditions are met

Example of elif

 holiday_name = input('What holiday is it today:')


 if holiday_name == 'Valentine's Day':
     print('Buy roses')
     print('watch movie')
     udyima = int(input('Enter 0 for False, Input 1 represents True:'))
     if udyima == 0:
         print('These days are inconvenient,Can't go to Confucianism')
     elif udyima == 1:
         print('ha-ha....You can go to Confucianism!!! so happy')
     else:
         print('alas...It's hard to understand a woman's mind!!!!!!')

 elif holiday_name == 'Christmas':
     print('Eat Christmas dinner')
     print('giving gifts.')
     print('watch movie')
     print('De Confucianism')

 elif holiday_name == 'birthday':
     print('Send birthday cake')
     print('giving gifts.')
     print('watch movie')
     print('De Confucianism')

 else:
     print('ah!!!It's not a holiday at last! Don't go to Confucianism! So tired!! It needs mending!!!')

while Loop

# Define a counter
 i = 1

 while i <= 100:  # When the conditions are met, the code in while will be executed
     print('I Love You')     # Code that needs to be executed repeatedly

     i += 1  # There must be a counter. Without a counter, it is likely to cause an endless loop


# Three processes of procedure
# There are three processes in program development
# 1. Sequence -- execute the code in sequence from top to bottom
# 2. Branch -- determine the branch to execute the code according to the condition judgment
# 3. Loop -- make specific code execute repeatedly

# Dead loop: because the programmer forgets to modify the judgment conditions of the loop inside the loop, the loop continues to execute and the program cannot be terminated

# Counting in Python (program): counting from 0
# Natural counting starts from 1


# Calculate the cumulative sum of all numbers between 0-100
# 0+1+2+3+4+5+6+7+8+9.....+100


# Calculate the sum of all even numbers between 0 and 100
# Define a counter
 i = 0  # i is the counter
 s = 0   # s is the container where the results are stored

 while i <= 100:  # When the conditions are met, the code in while will be executed
     # print('I Love You')     # Code that needs to be executed repeatedly

     if i % 2 != 0:
         s += i

     i += 1  # There must be a counter. Without a counter, it is likely to cause an endless loop

 print(i)
 print(s)


# Break and continue are special keywords used in the loop. They are only valid in the current loop

# When the break condition is met, exit the loop and do not execute the following repeated code
# continue when the conditions are met, skip the current cycle and enter the next cycle


 i = 0

 while i < 10:
     if i == 7:
         i += 1
         continue
     print(i)
     i += 1

# While nesting means that while is nested inside while
# The external while affects the operation of the internal while loop. The external loop will not be executed until the internal loop does not meet the conditions

for loop

# for loop
# In Python, the for loop can traverse any sequence of items, such as a list or in characters

# Format of for loop
# for temporary variable in list or characters:
#     The code to be executed when the loop meets the conditions
# else:
#     Execute code that does not meet the conditions

 str_1 = '123456789'

 for i in str_1:
     if i == '8':
         continue
     print(i)
 else:
     print('When all the contents in the string are traversed, the conditions are not met and will be executed else')

 # Range means range
 for i in range(1, 3):
     for j in range(1, 3):
         for s in range(1, 3):
             print(i, j, s)

list

# List: brackets
 a = 'xiaoming'
 list_1 = []
 list_2 = list()
 list_3 = ['xiaohong', 'lisi']
# Add: add data to the list
# append add to the end
 list_3.append('zhangfei')
 print(list_3)

# insert
 list_3.insert(0, 'machao')
 print(list_3)

 b = ['liubei', 'zhaoyun']
 list_3.extend(b)
 print(list_3)
 a = [1, 2, 3, 4, 5, 6, 7, 8]
 b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

 for i in a:
     b.insert(i, a[i-1])
 print(b)


# Take the elements in the list according to the subscript (Note: the subscript starts from 0)
 print(b[2])
 print(b[3])
 print(b[4])

# Left closed and right open, taking values in turn
 print(b[2:4])
 print(b[2:6])
 print(b[2:8])

 ['c', 'd', 'e', 'f', 'g', 'h']
# Select step by step
# Subscript 0, 2, 4, 6, 8
 print(b[2:8:2])
# Subscript 0, 3, 6, 9
 print(b[2:8:3])
# Subscript 0, 4, 8, 12
 print(b[2:8:4])

 b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

 print(b[-4:])
 print(b[:-4])

# Delete remove
 b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
 print(b.remove(b[0]))
 b.remove(b[0])
 print(b)
 del b[0]
 print(b)


# Delete last value
 a = b.pop()
 print(a)
 b[3][0] = 'zhangfei'
 print(b)
 a = b.pop(3)
 print(a)

# Modified according to = assignment
 b = [['xiaoming', 18, 'male'], ['xiao red', 18, 'female'], ['Li Si', 18, 'male'], ['Fei Zhang', 18, 'male']]
 c = b[2][0].replace('Li Si', 'lisi')
 print(b)
 b = 888
 c = 889-1
 print(id(b))
 print(id(c))
# is = = difference

# index, in, not in

 print(len(b))
 if '3' in b:
     num = b.index('3')
     print(num)
 for i in b:
     print(i)
 a = 'qwertyuiasdfgasfsafafsafasfafsafafhjkzxcvbnm'
 num = len(a)
 print(num)

 for j in b:
     print(b.index(j))
       print(j)
       str_1 = b[j]
       print(str_1)

 b = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '3']
 i = 0
# The length is 9 and there are 9 data
 print(len(b))

 while i < len(b):
     print(b[i])
     i = i + 1

tuple

# Tuples: parentheses that cannot become data types
# When there is only one value in the tuple, you need to add one after it,
 a = tuple()
 b = (2,)

 print(type(a))
 print(type(b))

 a = (1, 2, 3, 4, 5)
 b = list(a)
 b[0] = 'g'
 c = tuple(b)
 print(c)


 a = ('a', 'b', 'c', 'd', 'd', 'e', 'e')
 print(a.index('b'))

 print(a.count('d'))

Dictionaries

# Dictionary: curly braces are outside
# The form of key value pair exists
# What is a key: value pair
# c = {'key': 'value'}


 a = {'name': 'xiaoming'}
 b = dict()

# add to
 a['age'] = 20
 print(a)
 a = {'name': 'xiaoming', 'age': 20}
 a['age'] = 18
 print(a)

# Conclusion: add data to the dictionary. If the key value exists, it will be modified. If it does not exist, it will be created

 c = str_1.split('; ')
 print(c)
# Dictionary derivation
 result = {i.split('=')[0]: i.split('=')[1] for i in str_1.split('; ')}
 print(result)
 a = {}
 for i in str_1.split('; '):
     i.split('=')

 a = 'xiaoming 20 male'
 b = a.split(' ')
 print(b)
 print(str_1.split('; '))

# Dictionary deletion

 del a['name']
 print(a)
 a.clear()
 print(a)

 for i in a.values():
     print(i)
 print('*********************************')
 for j in a.keys():
     print(j)

 print(a.items())
 for i in a.items():
     for j in i:
         print(j)
 for i in a.keys():
     print(i)

     a['name'] = 'name' + '1'
 print(a)
 a = {'name': 'xiaoming', 'age': 20, 'sex': 'male', 'number': 0}
 in
 not in

 a = {'name': 'xiaoming', 'age': 20, 'sex': 'male', 'number': 0}
 for i in a.keys():
     if 'name' in i:
         print(6666666666)
     if 'name' not in i:
         print(8888888888)

aggregate

# Set, with curly braces on the outside
# Features: de duplication. The collection is out of order and does not support subscript (index) operations
 a = set()
 b = {1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 5, 5, 5, 1, 1, 1, 1}
 print(b)

# Application scenario: the URL (URL, link) address of the crawler is de duplicated
# Add element
 a.add('xiaoming')
 a.add('18')
 print(a)

 b.remove(6)
 print(b)

# nesting
 a = [[{'name': 'x', 'age': 18, 'sex': 'male'}], [{'name': 'y', 'age': 18, 'sex': 'male'}], [{'name': 'z', 'age': 18, 'sex': 'male'}]]

 print(type(a[0]))
# Note that collections and dictionaries cannot exist at the same time
 a = {{'name': 'xiaoming'}}
 print(a)

 a = [[{'name': 'x', 'age': 20, 'sex': 'male'}, {'name': 'a', 'age': 21, 'sex': 'male'}],
      [{'name': 'y', 'age': 19, 'sex': 'male'}, {'name': 'b', 'age': 22, 'sex': 'male'}],
      [{'name': 'z', 'age': 18, 'sex': 'male'}, {'name': 'c', 'age': 23, 'sex': 'male'}]]
 print(a[1])
 print(a[1][0])
 print(a[1][0]['name'])

 print(a[2][1]['age'])

 a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 j = 0
 for i in a:
     j += i
 print(j)
 print(sum(a))

Operator public method

"""Operator public method"""
# +Support: string, list and tuple. Addition is not supported for different data types
 a = 'zhang'
 b = 'fei'
 c = b + a
 print(c)
 aa = '1'
 bb = '2'
 cc = aa + bb
 print(cc)
 #For numbers, it is plus, and for characters, it is splicing
 a = (1, 2, 3, 4, 5, 6)
 b = ['a', 'b', 'c']
 print(a + b)
 a = {'name': 'xiaoming'}
 b = {'age': 18}
 print(a + b)


# *Support: string, list, tuple
 a = 2
 print(a ** 3)
 a = 'qwertyuio'
 print(a * 2)
 b = [1, 2, 3]
 print(b * 2)
 c = {1, 2, 3}
 print(c * 2)

 # in support: string, tuple, list, dictionary, collection
 a = [1, 2, 3, 4, 5, 8]
 if 1 in a:
     print(666)
 a = {'name': 'xiaoming', 'age': 18}

in operation on dictionary

'''be careful: in When operating on a dictionary, the default judgment is the value of the dictionary key value'''
 if {'name': 'xiaoming'} in a:
     print(666)
 else:
     print(888)
 a = (1, 2, 3, ('a', 'b', 'c'))
 b = ('a', 'b', 'c')
 if b in a:
     print(666)
 else:
     print(888)

# Dictionaries and collections cannot coexist
 a = {'key': ({'name': 'xiaoming'}, {'name': 'xiaoming'}), 'keys': {'age': 18}}
 b = 'name'
# Not all key s in a dictionary are judged
 if b in a.keys():
     print(666)
 else:
     print(888)


# not in support: string, tuple, list, dictionary, collection
 a = {1, 2, 3}
 b = 3
 if b in a:
     print(666)
 else:
     print(888)
 a = {{'name': 'xiaoming'}}
 print(a)

python built-in functions

"""python Built in function"""
# len number of statistical elements (data)
 a = (1, 2, 3, 4, 2)
 print(len(a))

# max returns the maximum value in the container
 a = ['b', 'f', 'e', '2']
 b = max(a)
 print(b)
# min returns the minimum value in the container
 a = ['b', 'f', 'e', '2']
 b = min(a)
 print(b)

# del delete

# sum
 a = [1, 2, 3, 4, 5, 7]
 b = sum(a)
 print(b)

Variable type and immutable type

"""References: mutable and immutable types"""
# If you change the data structure, will the memory address change

# What is the difference between is and = =?

 a = 999
 b = 1000 - 1
 if a is b:
     print(666)
 if a == b:
     print(888)
# Is is to judge whether the memory space of the two is the same
#  ==Is to judge whether the two values are equal



# Adding data to lists and dictionaries does not change memory space, that is, variable data types
 list_1 = [1, 2, 3, 4, 5]
 print(id(list_1))
 list_1.append('f')
 print(id(list_1))

 a = {'name': 'xiaoming'}
 print(id(a))
 a['age'] = 18
 print(id(a))

# Immutable type: string, tuple: changing its structure will produce a new data
 a = 'xiao'
 print(id(a))
 print(id(a + 'sdsad'))
 b = (1, 2, 3)
 c = (1, 2, 3)
 print(id(b))
 print(id(c))
 a = ['xiaomin', 'female']
# Immutable data type: store account information, bank card information, password information, key, etc
# Variable data type: personal information

Ternary operators: ternary expressions

"""Ternary operators: ternary expressions"""
# Return True to execute if expression else return False to execute

 print('I'm in your heart' if 3 > 4 else 'You are not in my heart')


print(i for i in range(10) if i % 2 != 0 )

 list_1 = []
 for i in range(10):
     if i % 2 != 0:
         list_1.append(i)
     else:
         list_1.append('s')
 print(list_1)







 x = 3
 y = 5
# Execution sequence: from left to right
 print('I'm older than you' if x > y else 'What a nice day today' if x == y else 'It's raining today')
 if x>y:
     print('I'm older than you')
 else:
     if x == y:
         print('What a nice day today')
     else:
         print('It's raining today')
# The problem of verification: the execution order of nested ternary operators
# 1 output from left to right I'm bigger than you
# 2 output from right to left. It's raining today

 a = 1
 b = 2
 print('you are so good'if a > b else 'Very embarrassed' if a == b else 'Cried' if a < b else 'Win')
 if a > b:
     print('you are so good')
 else:
     if a == b:
         print('Very embarrassed')
     else:
         if a < b:
             print('Cried')
         else:
             print('Win')

function

Use of functions

#Use of functions
# 1) Definition of function
# def Function name():   #Function name: letter_ Figures_ Underline and the number cannot begin (see the meaning of the name), large_ Small hump method
#     Code block 1 for realizing independent functions
#     ...
#     Code block 2 for realizing independent functions
#Once defined, it will not run without calling


# 2)Function call: directly use the function name()  #Method call: through variable point method, list_2.append((x, y))
# FoZu()  #The code run jumps to the function definition

Return value of function

#Return value of function
def sum_1():
    a = 1
    b = 2
    c = a+b
    return c  #Stop the function. return returns the result of the function (multiple data types)


# print(sum_1())  #Print directly to None, and sum is required_ 1 = 3

Parameters of function

#Function parameters: variables that need to be used in the code to define the function implementation function
# def function name (parameter 1, parameter 2,..., parameter n):
#     Code block 1 for realizing independent functions
#     Use parameter 1
#     ...
#     Use parameter 2
#     Code block 2 for realizing independent functions

def sum_2(a, b):
    return a+b

 print(sum_2(123456787654321,123456787654321))

#Properties of parameters: formal parameters and arguments
def sum_3(a, b):  #Formal parameter (formal parameter): the parameter used in function definition is called formal parameter (placeholder)
    return a+b

 print(sum_2(63,12345321))  #Argument (actual parameter): the parameter actually passed in when calling the function

#Type of parameter:
#Required (position) parameter: the parameter that must be used when calling the function, which is different from the function defined by the code block (the parameter position is wrong, the result is different, or even an error is reported)
def division(a, b):  #division: division
    return a/b


 print(division(1,3))


 print(division(1, 2))
 print(division(2, 1))


 print(division(1,0))
 print(division(0,2))

#Default parameter: the default value of the parameter is given when the function is defined. When a new parameter is passed in when the function is called, the parameter will be updated. If it is not passed in, the default value at the time of definition will be used (reference parameters in order)
def sum_4(a=1, b=2):
    return a+b

# num_1 = 67
num_1 = 23
 print(sum_4(4, 5))
 print(division())
 print(sum_4())  #It can be used directly without transferring parameters

#Enter only a single
 print(sum_4(66))


#Parameters and default parameters must be mixed to follow the order. When defining and calling, the default parameters come first.
def sun_6(a,b=1):
    pass

#Keyword parameter: similar to the default parameter when defining, it is passed in the form of key value pairs, regardless of the parameter position (order)
def sum_5(a=1, b=2):
    return a+b


 print(sum_5(a=3, b=7))
 print(sum_5(b=7, a=3))  #When using keyword parameters, bring keywords




#Indefinite length parameter: when defining, the number of parameters passed in is uncertain
def Func(*args, **kwargs):  #*The number of Representatives is uncertain, * args uses tuple to receive parameters, * * kwargs: uses dictionary to receive parameters
    print(args)
    print(kwargs)

 Func(1, 2, 3, a=4, b=5, c=6)  #Two receiving methods are designed to solve the problem of multiple parameter input

# Function type: it is judged according to whether the function has parameters and return value
# With parameter and return value A
# No parameter with return value B
# With or without parameter return value C
# No parameter, no return value D

Nesting of functions

#Nesting of functions: call other functions when a function is defined
def sum_7():
    return 2+3

# print(sum_7())
def sum_8(d):
    return sum_7()*d

print(sum_8(5))

variable

#Scope of variables: in which part can the program access which specific variables
#Global variables: directly define variables that can be referenced anywhere in the code file


# Local variables: they can only be accessed in a specific area (learned before tomorrow: inside / outside the function), and variables defined in the function can only be accessed in the function
def sum_1():
    num_1 = 99
    print(num_1)
 sum_1()
 print(num_1)


#Global variables and local variables have the same name: local variables with the same name do not go back to overwrite the global variables, and local variables are preferred (strong dragons do not suppress local snakes)
num_2 = 98
def sum_2():
    num_2 = 19
    print(num_2)
 sum_2()
 print(num_2)

#Global: change local variable to global variable (snake wants to turn dragon)
def sum_3(a,b):
    global num_2  # Modified
    num_2 = a+b
    print(num_2)

 sum_3(2,3)
 print(num_2)

Recursive function

#Recursive (algorithmic) function: the function calls itself. (if you want to understand recursion, you must understand recursion first)
#One question 👉 Continue to disassemble into small problems 👉 Solve a small problem 👉 Solve the whole problem
#Once upon a time, there was a mountain and a temple in the mountain. There was an old monk telling a story in the temple. What was the story?
# while True:
#     Once upon a time, there was a mountain and a temple in the mountain. In the temple, an old monk was telling a story. What was the story

#Recursive function requirements:
#1. There must be a clear end condition (exit), or it will be a dead cycle
#2. When entering a layer of recursion, the scale of the problem is smaller than that of the previous one

#Define the function to calculate factorial 5= 5 x 4 x 3 x 2 x 1
def factorial(num):
    i = 1
    result = 1
    while i < num:
        i += 1
        result *= i
    return result
# print(factorial(20))

#Recursive functions that define factorials
def factorial_2 (num):
    if num >= 1:
        result = num*factorial_2(num-1)
    else:
        result = 1
    return result
# print(factorial_2(5))
# Problem: 5= 5 x 4 x 3 x 2 x 1
# Return result: return result = 1 x 2 x 3 x 4 x 5
#Call the function, num=5, and execute the following code block if the condition of num > = 1 is met
#Call the factorial function. At this time, the parameter num = 5-1=4 meets the condition of num > = 1. Execute the following code block
#Call the factorial function again. At this time, the parameter num = 4-1=3 meets the condition of num > = 1, and execute the following code block
#Call the factorial function again. At this time, the parameter num = 3-1=2 meets the condition of num > = 1, and execute the following code block
#Call the factorial function again. At this time, the parameter num = 2-1=1 meets the condition of num > = 1. Execute the following code block
#Call the factorial function again. At this time, the parameter num = 1-1=0 does not meet the condition of num > = 1. Execute the code under else
'''Five function calls are running at the same time'''
#Execute return and else to reset the result to 1 and return the result to the previous level

Anonymous function

#Anonymous function: when defining a function, it is not defined in the form of def keyword
def sum_99(a, b):
    return a+b
# print(sum_99(4,5))
# print(type(sum_99(2,3)))
#Anonymous function name = lambda parameter 1, parameter 2: function code
sum_99_1 = lambda x, y : x+y
# print(sum_99_1(4, 5))

#Nesting of anonymous functions
sum_99_99 = lambda num_1:(lambda num_2:num_1+num_2)
#Nested anonymous function calls
number_1 = sum_99_99(4) #Layer 1 call
print(type(number_1))  #At this time, the object called for the first time also becomes a function, number_ 1 = lambda 4,num_ 2:num_ 1+num_ two
print(number_1(5))

def sum_num_1(num1):

    def sum_num_2(num2):  #Another method of function nesting is to define sub functions in the function body
        return num1+num2

    return sum_num_2(5)

# print(sum_num_1(4))

sum_99_99 = lambda num_1:(lambda num_2:num_1+num_2)

One of the design ideas of python: fully calling computer functions

#One of the design ideas of python: fully calling computer functions
#File operation: open, read, write, close (to reduce the waste of memory resources)

#Open file: open(), enter the path in quotation marks
 file = open('test.txt','w',encoding='utf8')


#Read: read()
 file_str = file.read()
 print(file.read())

 file = open('test.txt','r',encoding='utf8')
#Read a line: readline
 print(file.readline())

#Read the entire file as a line and return to the list: realines
 print(file.readlines())

#Write: write()
 file.write('aaa')  #Writing directly overwrites the original content

#Close: close
 file.close()

#open('File name ',' access mode parameter ',' encoding format '): access mode permission parameter
# r read only
# w write only. If the file does not exist, a new file will be created. Direct writing will overwrite the contents of the original file
# A append. If the file does not exist, a new file will be created and written at the end of the file 👉 field name pointer
# rb/wb/ab(binary system): read, write and append files in binary mode
# r+/w+/a+/rb+/wb+/ab +: move the file pointer to the beginning




#File pointer: records the location of reads and inputs
#When you open a file for the first time, the file pointer usually points to the beginning of the file
#After the read method is executed, the file moves to the end of the read content

 file = open('test.txt','r+',encoding='utf8')
 print(file.read())
 print(file.tell())  #Detect the location of the current file pointer
 print('*'*50)
 file.seek(10)  #Change the file pointer position, 0 represents the beginning
 print(file.read())

#File copy
 file = open('test.txt','r',encoding='utf8')
 file_str = file.read()
 file_1 = open('test1.txt','w',encoding='utf8')
 file_1.write(file_str)
 file.close()
 file_1.close()

exception handling

# Exception handling: the function in python specially used to handle errors and exceptions in the program, which can be used for program debugging
# Exception: when the program is running, the python interpreter encounters an error, stops running and prompts an error message

# Syntax error: out of specification
# Running error: the error that may occur when the program is complex
# Semantic error: when programming, there is an error in translating requirements into code logic. The operation results are inconsistent with the expected results


#Attributeerror: an error that will be raised when the attribute reference and assignment fail
 tuple_1 = (1,2,3)
 tuple_1.append('7')

#Name error: an attempt was made to access a variable that does not exist
 print(a)

#IOError: file does not exist

#Keyword error: a keyword (key name) that does not exist in the mapping is used
 dict_1 = {'a':1,'b':2}
 print(dict_1['c'])

#Valueerror: the parameter type passed to the object is incorrect
 int('asdfgh')

#Index error: the index used does not exist
 list_1 = [1,2,3]
 print(list_1[99])

#Type error: the type of function application and error
 age = 18
 print('My age is' + 18)


# Catch exceptions: it can ensure the stability and robustness of the program (robustness: the load capacity of a program)
#Single exception capture
# try-except
 try:
     Code with possible exceptions
 except:
     Write custom prompt
 try:
     age = 18
     print('My age is' + 18)
 except TypeError:
     print('Type error here, at 116-117')
 print('aaa')

#During programming, it is impossible to predict all exceptions
#Multiple exception capture
 try:
     int('asdfghj')
     age = 18
     print('My age is' + 18)
 except Exception as Error:   #Rename the object and customize the name (see the meaning of the name)
     print('An exception occurs here. The line number is 125-127')
 try:
     int('asdfghj')
     age = 18
     print('My age is' + 18)
 except:
     print('An exception occurs here. The line number is 125-127')

# try-except-else-finally
 try:
     int('asdfghj')
     age = 18
     print('My age is' + 18)
 except Exception as Error:   #Rename the object (see the meaning of the name)
     print('An exception occurs here. The line number is 125-127')
 else:
     print('I print only when there are no exceptions')
 finally:
     print('I'll run it whether there are exceptions or not')

#Transitivity of exception: when an exception occurs during function / method execution, the exception will be passed to the caller
def sum_1():
    return 3/0
def sum_2():
    return 5*sum_1()
 sum_2()

#Custom exception thrown: raise
#The user is required to enter a password. Password rule: the length must be greater than six digits (an exception will be thrown if the length is less than six digits)
 def u_i_p():
     pwd = input('Please enter a password with no less than six digits:')
     if len(pwd) >=6:
         return 'Password input meets the specification'
     ex = Exception('The password length is less than six digits')  #Custom exception
     raise ex  #Custom exception thrown

 try:
     print(u_i_p())
 except Exception as Error:
     print('Errors found:%s' % Error)
     u_pwd = u_i_p()


#with open: ensure that the code will be called if the code is closed close()
#Try finally: very cumbersome
 try:
     f = open('test1.txt','r')
     print(f.read())
 finally:
     print(1)
     f.close()
     f.read()

 with open('test1.txt','r') as f:
     print(f.read())

 print(f.read())

object-oriented programming

#object-oriented programming

#Process oriented programming: when solving a problem, first analyze the steps to solve the problem, then use the function to realize the steps step by step, and finally call the function in turn
#Process oriented has two characteristics: process oriented and modular
#Divide requirements into two steps
def print_1():
    print('Process oriented first step')

def print_2():
    print('Process oriented second step')

 print_1()
 print_2()

#Object oriented programming: encapsulating process oriented programming (encapsulating functions into classes)
#When object-oriented programming thinking solves the problem again, it will divide the problem into one object and define the method according to the responsibility of the object
#The three characteristics of object-oriented are encapsulation, inheritance and polymorphism
class Print:
    def print_1(self):
        print('Object oriented method I')

    def print_2(self):
        print('Process oriented approach II')

 print_ = Print()  #create object
 print_.print_1()  #Call method

 a = ['asdfg']  #create object
 a.sort()  #Call method


#To learn object-oriented programming well:
# Understand the concepts of classes and objects
#Class: class is the general name of a group of things with the same characteristics or behavior. It is abstract and cannot be used directly 👉 Drawings for manufacturing trolley (with various data and manufacturing methods)
#Object: the physical object created by the class. The class created by the object has the characteristics and behavior of the class 👉 Trolley

#Features: attributes
#Behavior: method


#Define class:
#1. Class name: big hump nomenclature
#2. Class
#3. Class

# class name:
#
#     def function name (self):
#         pass  #Specific function code

class Car:  #Define class
    car_brand = 'Benz'  #Define attributes
    def move(self):  #method
        print('One foot of the accelerator soared to 200 yards')

    def toot(self):  #method
        print('The car is whistling')

# create object
 benz = Car()
 benz.move()


#Differences between functions and methods:
#Definition: the defined functions belong to the whole file (top grid). The functions defined in the class are called methods and belong to this class
#Call: function call directly uses the function name (), and the calling object name of the method Method name ()


#__ init__ And self:
#__ Method name__ It belongs to the built-in method
#__ init__  Initialize the object, which is automatically called when the object is created
#self refers to the instance object itself. This parameter does not need to be input (one of the identifiers that distinguish functions and methods)
class Car_:  #Define class
    color = 'pink'  #Define class properties
    def __init__(self, brand):
        self.car_brand = brand  #Define instance properties

    def move(self):  #method
        # car_brand = 'Ferrari' defines the variable
        print('my{}One foot of the accelerator soared to 200 yards'.format(self.car_brand))


    def toot(self):  #method
        print('The car is whistling')

 ferrari = Car_()
 banz = Car_('Banz')
 banz.move()  #Call method

#Access properties
 print('My Mercedes color is{}'.format(banz.color))
#modify attribute
 banz.color = 'red'
 print(banz.color)
#Add attribute
 banz.wheelnum = 4
 print(banz.wheelnum)


#python modules, packages and libraries
#Module: py file
#Packages: including__ init__.py file folder
#Library: a collection of related functional modules,
class ob:
    def o(self):
        print('Find an object before the new year')

Concepts related to attributes and methods

#Concepts related to attributes and methods

#Class properties and instance properties
#Attributes belonging to a class (class variables) are created directly in the class
#Instance attribute: it belongs to the instance object itself, which is passed through self Property name creation
class Car_:  #Define class
    color = 'pink'  #Define class properties
    def __init__(self, brand):
        self.car_brand = brand  #Define instance properties

    def move(self):  #method
        # car_brand = 'Ferrari' defines the variable
        print('my{}One foot of the accelerator soared to 200 yards'.format(self.car_brand))


    def toot(self):  #method
        print('The car is whistling')

ferrari = Car_("Ferrar911")
 print(Car_.color)  #Access class properties by class name
 print(Car_.car_brand)  #The instance property cannot be accessed through the class name. The instance property belongs to the instance object itself
 print(ferrari.car_brand) #Access instance properties by object name
 print(ferrari.color) #Access class properties by object name


#Private properties and methods:
#Private attributes are used to protect the security of attributes 👉  tuple
#Attribute modification: direct modification and indirect modification

class Person_:
    age = 18
    def person_info(self, name, age, gender):
        print('full name:{}\n Age:{}year\n Gender:{}\n'.format(name, age, gender))

 qingshan = Person_()
 print(qingshan.age)
 qingshan.age = 17  #directly modify
 print(qingshan.age)
 qingshan.person_info('lush mountain', '18', 'male') #Indirect modification
 qingshan.person_info('lush mountain', '28', 'male')
 print(qingshan.age)

#If a property in a class does not want to be modified externally, you can define the property as private
#Define private: add before identifier__


class Person_girlfriend:

    def __init__(self, age, weight):
        self.__age = age  #Private attribute definition
        self.__girlfriend_weight = weight   #Private attribute definition
        age_True = 28

    def __weight(self):  #Define private methods
        print('Weight:{}'.format(self.__girlfriend_weight))

    def girlfriend(self): #Define public methods to access private properties and methods
        self.__weight()
        print(self.__age)  #Access private properties



 xiaofang = Person_girlfriend(18, 79)
 print(xiaofang.__age) #Private properties cannot be accessed
 xiaofang.__weight()  #Private method cannot be called
 xiaofang.girlfriend()  #Define public methods to access private properties and methods



#Magic method:__ Method name__ Belongs to built-in methods (some specific methods: perform specific operations and call automatically)

#__ init__ Method initializes the instance object after each instance object is created, not the constructor of the class
class Car:  #Define class

    def __init__(self, brand,color):  #Initialize the instance object
        self.car_brand = brand  #
        self.color = color

 banz = Car_('Banz')


#__ del__ Method destroys the instance object in memory and will be called automatically

class Person_del:
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def person_info(self):
        print('full name:{}\n Age:{}year\n Gender:{}\n'.format(self.name, self.age, self.gender))

    def __del__(self):
        print('Object destroyed....')

 qingshan = Person_del('lush mountain', 18, 'male')
 qingshan.person_info()
 qingshan

 import gc #Really free memory
 a = 1
 del a
 gc.collect()


#__ str__ Method returns the description information of the object, which needs to be output by the print() function and written to return
class Person_str:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return 'I am Person_str Class. My name is{}'.format(self.name)

 qingshan = Person_str('lush mountain')
 print(qingshan)


#__ new__ The constructor of the method class will be called automatically when creating an object__ init__ Call in__ new__, Generally, it is not rewritten
#You must pass a parameter cls
#self: instance object itself
#cls: the class itself

#Process for creating objects:
# 1. Call first__ new__ Get an object
# 2. Re call__ init__ Method to add instance properties to an object
# 3. Assign this object to the variable name

#Singleton design pattern: there is only one instance object (a globally used class is frequently created and destroyed)
#When to use: control the number of instances and save system resources

class Person_new():
    count_1 = None
    def __new__(cls, *args, **kwargs):
        if cls.count_1 is None:
            cls.count_1 = super().__new__(cls)
        return cls.count_1

    def __init__(self):
        self.age = 18
 qingshan = Person_new()
 xiaofang = Person_new()
 print(id(qingshan))
 print(id(xiaofang))

# Object oriented: process oriented
# Encapsulation: class, object, attribute, method
# Inheritance: single inheritance, multiple inheritance

# Job: create a car class: attributes: number of tires, color, weight, maximum fuel tank capacity
#                     Method: refuel and accelerate

#               Create Ferrari class: inherited from the car. The method needs to be rewritten: there is maximum fuel for refueling and acceleration


class Auto(object):
# Heaven, water
    def __init__(self, color, weight, fuel_capacity=0, tire=4):
        self.color = color
        self.weight = weight
        self.fuel_capacity = fuel_capacity
        self.tire = tire

    def add_fule(self, value):
        self.fuel_capacity += value
        if self.fuel_capacity >=200:
            self.fuel_capacity = 200
            print('It's full')

    def add_speed(self, values):
        print(f'100 km acceleration of ordinary vehicles{values}second')



class Ferrari(Auto):
#Rewriting is not recommended__ init__ Method, you can add instance properties through the instance object
    def __init__(self):
        super(Ferrari, self).__init__(color='pink', weight=200, fuel_capacity=50, tire=4)

    def add_fule(self, value):
        self.fuel_capacity += value
        if self.fuel_capacity < 120:
            print('emmm,Not full')
        elif self.fuel_capacity == 120:
            print('Burp~~!It is just fine')
        else:
            self.fuel_capacity = 120
            print('I'm fullΣ(っ °Д °;)っ')

    def add_speed(self):
        print('It only takes me five seconds to accelerate a hundred kilometers')

# LSP principle basic object-oriented design principle: inheritance only focuses on step rewriting


 ferrari911 = Ferrari()
 s.add_fule(30)  #fule=50,80
 s.add_fule(40)  #120





# polymorphic
# Three characteristics of object-oriented programming
# Encapsulation: more importantly, attributes and methods are encapsulated into an abstract class
# Inheritance: realize code reuse, do not need to write repeatedly, and can be expanded
# Polymorphism: different subclass objects call the same parent method to produce different execution results (it can increase code flexibility, and polymorphism depends on inheritance)

# Characteristics of polymorphism: only care about whether the instance method of the object has the same name. Polymorphism is a calling skill and will not affect the internal design of the class

# Human beings, themselves

class Person(object):

    def __init__(self, age):
        self.age = age

    def eat(self):
        print('If you are a person, you have to cook')

    def sleep(self):
        print('It's a person who has to sleep and rest')


class Son:

    def eat(self):
        print('As children, eat on time and honestly')

    def sleep(self):
        print('Be honest, go to bed early and get up early')


class Soul_Mate:

    def eat(self):
        print('Having dinner with a heterosexual partner is more romantic')

    def sleep(self):
        print('Go to Confucianism happily')

class Friend:

    def eat(self):
        print('When you go to dinner with friends, you have to get a basin')

    def sleep(self):
        print('What are you sleeping for? Get up. Hey, I'm stone, you Asso')


def sleep(obj):
    obj.sleep()

 role_1 = Son()
 sleep(role_1)
 role_2 = Soul_Mate()
 sleep(role_2)
 role_3 = Friend()
 sleep(role_3)

# Class is also an object
# Class methods and static methods

# Class method: the decorator is required for the method of operating the class itself. The first parameter of the class method is cls
# Suppose there is a method that logically uses the class itself as an object to call
class Class_Method():
    def __init__(self):
        pass
    @classmethod
    def info(cls):
        print('Calling class method')

    def info_(self):
        pass

Class_Method.info()
s = Class_Method()
s.info()

# Static method (can be understood as a function): you do not need to access instance properties and call instance methods, nor do you need to access class properties and call class methods (similar to _str _)
# Static methods are used to store logical code and logically belong to classes. In fact, they have nothing to do with the class itself
#
class Static_Method(object):
    @staticmethod
    def info():
        print('Calling static method')

Static_Method.info()
s = Static_Method()
s.info()

# try-with open

def readFile(filename):
    try:
        with open(filename, 'r', encoding='utf8') as f:
            print(f.readlines())
    except:
        print('You have a problem')
readFile('test.txt')


I wish you all success in learning python!!

Keywords: Python string OOP list

Added by erikhillis on Fri, 28 Jan 2022 05:16:09 +0200