Basic knowledge of Python (3)
(1) Cycle structure and selection structure
1. Conditional expression
Most legitimate Python expressions can be used as conditional expressions.
In the selection and loop structure, the Python interpreter considers that the value of the conditional expression is equivalent to True as long as it is not False, 0 (or 0.0, 0 j, etc.), null value None, empty list, empty tuple, empty collection, empty dictionary, empty string, empty range object or other empty iterative objects.
>>> if 666: #Use integer as conditional expression print(9) 9 >>> a = [3, 2, 1] >>> if a: #Use list as conditional expression print(a) [3, 2, 1] >>> a = [] >>> if a: #An empty list is equivalent to False print(a) else: print('empty') empty >>> i = s = 0 >>> while i <= 10: #Use relational expressions as conditional expressions s += i i += 1 >>> print(s) 55 >>> i = s = 0 >>> while True: #Use the constant True as a conditional expression s += i i += 1 if i > 10: #Use the break statement to exit the loop when certain conditions are met break >>> print(s) 55 >>> s = 0 >>> for i in range(0, 11, 1): #Traversal sequence elements s += i >>> print(s) 55
(1) Relational operator
The relational operators in Python can be used continuously, which not only reduces the amount of code, but also conforms to the human way of thinking.
>>> print(1<2<3) #Equivalent to 1 < 2 and 2 < 3 True >>> print(1<2>3) False >>> print(1<3>2) True
In Python syntax, the assignment operator "=" is not allowed in conditional expressions, which avoids the trouble caused by mistakenly writing the relational operator "= =" into the assignment operator "=". Using the assignment operator "=" in the conditional expression will throw an exception and prompt for syntax error.
>>> if a=3: #Assignment operators are not allowed in conditional expressions SyntaxError: invalid syntax >>> if (a=3) and (b=4): SyntaxError: invalid syntax
(2) Logical operator
The logical operators and, or and not represent logical and, logical or and logical non respectively. For and, the entire expression is equivalent to True only if the expressions on both sides are equivalent to True.
For or, as long as one of the expressions on both sides is equivalent to True, the whole expression is equivalent to True; For not, if the following expression is equivalent to False, the whole expression is equivalent to True.
The logical operators and and or have the characteristics of short-circuit evaluation or lazy evaluation. They may not evaluate all expressions, but only evaluate the expressions that must be evaluated.
>>> 3 and 5 #The value of the entire expression is the value of the last evaluated subexpression 5 >>> 3 or 5 3 >>> 0 and 5 #0 is equivalent to False 0 >>> 0 or 5 5 >>> not [1, 2, 3] #A non empty list is equivalent to True False >>> not {} #An empty dictionary is equivalent to False True
2. Select structure
Common selection structures include single branch selection structure, double branch selection structure, multi branch selection structure and nested branch structure. Jump tables can also be constructed to realize similar logic.
Loop structure and exception handling structure can also have "else" clause, which can be regarded as a special form of selection structure.
2.1 single branch selection structure
Write a program, enter two integers separated by spaces, and then output them in ascending order.
x = input('Input two number:') a, b = map(int, x.split()) if a > b: a, b = b, a #Unpack the sequence and exchange the values of two variables print(a, b)
2.2 dual branch selection structure
Solve the chicken rabbit cage problem.
jitu, tui = map(int, input('Please enter the total number of chickens and rabbits and the total number of legs:').split()) tu = (tui - jitu*2) / 2 if int(tu) == tu: print('Chicken:{0},Rabbit:{1}'.format(int(jitu-tu), int(tu))) else: print('Incorrect data, no solution')
Python also provides a ternary operator, and ternary operators can be nested in the expression composed of ternary operators, which can achieve the effect similar to the selection structure. Syntax is
value1 if condition else value2
When the value of the conditional expression condition is equivalent to True, the value of the expression is value1; otherwise, the value of the expression is value2.
>>> b = 6 if 5>13 else 9 #Assignment operators have very low priority >>> b 9
2.3 multi branch selection structure
Use the multi branch selection structure to change the score from the percentage system to the grade system.
def func(score): if score > 100 or score < 0: return 'wrong score.must between 0 and 100.' elif score >= 90: return 'A' elif score >= 80: return 'B' elif score >= 70: return 'C' elif score >= 60: return 'D' else: return 'F'
2.4 nesting of selection structures
Use nested selection structure to change grades from percentile system to hierarchical system.
def func(score): degree = 'DCBAAE' if score > 100 or score < 0: return 'wrong score.must between 0 and 100.' else: index = (score - 60) // 10 if index >= 0: return degree[index] else: return degree[-1]
3. Circulation structure
Python mainly has two forms of loop structures: for loop and while loop. Multiple loops can be nested, and they are often nested with the selection structure to realize complex business logic.
The while loop is generally used when it is difficult to determine the number of cycles in advance. Of course, it can also be used when the number of cycles is determined;
The for loop is generally used when the number of loops can be determined in advance, especially when enumerating or traversing elements in a sequence or iterative object.
For the loop structure with else clause, if the loop ends naturally because the conditional expression is not tenable or the sequence traversal ends, the statements in else structure will be executed. If the loop ends early because the break statement is executed, the statements in else will not be executed.
The complete grammatical forms of the two loop structures are: while Conditional expression: Circulatory body [else: else Clause code block] and for Value in Sequence or iteration object: Circulatory body [else: else Clause code block]
3.1 for loop and while loop
Write a program to output all integers between 1 and 100 that can be divided by 7 but can not be divided by 5 at the same time.
for i in range(1, 101): if i%7==0 and i%5!=0: print(i)
Write a program to print the 99 multiplication table.
for i in range(1, 10): for j in range(1, i+1): print('{0}*{1}={2}'.format(i,j,i*j), end=' ') print() #Print blank lines
3.2 break and continue statements
Once the break statement is executed, the loop of the level to which the break statement belongs will end in advance;
The function of continue statement is to end this cycle in advance, ignore all statements after continue and enter the next cycle in advance.
Write a program to calculate the maximum prime number less than 100.
for n in range(100, 1, -1): if n%2 == 0: continue for i in range(3, int(n**0.5)+1, 2): if n%i == 0: #End internal circulation break else: print(n) #End external circulation break
4. Comprehensive case analysis
Enter several grades and find the average score of all grades. After each score is entered, ask whether to continue to enter the next score. Answer "yes" to continue to enter the next score, and answer "no" to stop entering the score.
numbers = [] while True: x = input('Please enter a grade:') #Exception handling structure to ensure that users can only enter real numbers try: #First convert x to a real number, and then append it to the end of the list numbers numbers.append(float(x)) except: print('Not a legitimate achievement') #The following loop is used to restrict the user from entering "yes" or "no" in any case while True: flag = input('Continue typing? ( yes/no)').lower() #The lower function converts all uppercase letters in a string to lowercase letters if flag not in ('yes', 'no'): print('Only input yes or no') else: break if flag=='no': break #Calculate average score print(sum(numbers)/len(numbers))
Write a program to judge what day today is this year.
import time date = time.localtime() #Get current date and time print(date) year, month, day = date[:3] day_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if year%400==0 or (year%4==0 and year%100!=0): #Determine whether it is a leap year day_month[1] = 29 if month == 1: print(day) else: print(sum(day_month[:month-1])+day)
Write code to output the diamond pattern composed of asterisk * and flexibly control the size of the pattern.
def main(n): for i in range(n): print((' * '*i).center(n*3)) for i in range(n, 0, -1): print((' * '*i).center(n*3))
Quickly determine whether a number is a prime number.
n = input("Input an integer:") n = int(n) if n in (2,3): print('Yes') #Even numbers must not be prime numbers elif n%2 == 0: print('No') else: #Prime numbers greater than 5 must appear on both sides of the multiple of 6 #Because 6x+2, 6x+3 and 6x+4 are definitely not prime numbers, let's assume that x is a natural number greater than 1 m = n % 6 if m!=1 and m!=5: print('No') else: for i in range(3, int(n**0.5)+1, 2): if n%i == 0: print('No') break else: print('Yes')
Write a program, input a natural number n, and then calculate and output the factorial sum of the first n natural numbers, the value of 1! + 2! + 3! +... + n.
n = int(input('Please enter a natural number:')) #Use result to save the final result, and t represents each item result, t = 1, 1 for i in range(2, n+1): #Get the current item based on the previous item t *= i #Add the current item to the final result result += t print(result)
Write code to simulate the calculation process of the final score on the final scene. There are at least 3 judges, and the scoring rule is to calculate the average score of the remaining scores after deleting the highest score and the lowest score.
while True: try: n = int(input('Please enter the number of judges:')) if n <= 2: print('Too few judges,There must be more than 2 people.') else: break except: pass scores = [] for i in range(n): #This while loop is used to ensure that the user must enter a number between 0 and 100 while True: try: score = input('Please enter page{0}Scores of judges:'.format(i+1)) #Convert a string to a real number score = float(score) assert 0<=score<=100 scores.append(score) #If the data is legal, jump out of the while loop and continue to enter the score of the next judge break except: print('Score error') #Calculate and delete the highest and lowest scores highest = max(scores) lowest = min(scores) scores.remove(highest) scores.remove(lowest) finalScore = round(sum(scores)/len(scores),2) # round rounded to n decimal places formatter = 'Remove one of the highest scores{0}\n Remove a minimum score{1}\n Final score{2}' print(formatter.format(highest, lowest, finalScore))
(2) Functions
1. Function definition and basic calling syntax
Function definition syntax: def Function name([parameter list]): '''notes''' Function body matters needing attention Function parameters do not need to declare types, nor do they need to specify the return value type of the function You must keep a pair of empty parentheses even if the function does not need to receive any arguments The colon after the bracket is indispensable Function body relative to def Keywords must be indented with spaces Python Allow nested definition functions
Write the function to generate Fibonacci sequence and call.
def fib(n): a, b = 1, 1 while a < n: print(a, end=' ') a, b = b, a+b print() fib(1000)
2. Recursive function call
The recursive call of a function is a special case of function call. The function calls itself, calls itself again, calls itself again,... When a certain condition is met, it will not be called again, and then returns layer by layer until the position where the function is called for the first time.
Factorization of integers using recursive methods.
from random import randint def factors(num, fac=[]): #Find the factor from 2 each time for i in range(2, int(num**0.5)+1): #Find a factor if num%i == 0: fac.append(i) #Continue to decompose the quotient and repeat the process factors(num//i, fac) #Note that this break is very important break else: #It's indecomposable. It's also a factor fac.append(num) facs = [] n = randint(2, 10**8) factors(n, facs) result = '*'.join(map(str, facs)) if n==eval(result): print(n, '= '+result)
3. Function parameters
During function definition, there are comma separated formal parameters in parentheses. A function can have multiple parameters or no parameters, but a pair of parentheses must be provided during definition and call, indicating that it is a function and does not receive parameters.
When a function is called, arguments are passed to it. According to different parameter types, references to arguments are passed to formal parameters.
When defining a function, you do not need to declare the parameter type. The interpreter will automatically infer the parameter type according to the type of the argument.
3.1 location parameters
positional arguments are a common form. When calling a function, the order of arguments and formal parameters must be strictly consistent, and the number of arguments and formal parameters must be the same.
>>> def demo(a, b, c): print(a, b, c) >>> demo(3, 4, 5) #Pass parameters by location 3 4 5 >>> demo(3, 5, 4) 3 5 4 >>> demo(1, 2, 3, 4) #The number of arguments and formal parameters must be the same TypeError: demo() takes 3 positional arguments but 4 were given
3.2 default value parameters
When calling a function with a default value parameter, you do not need to pass the value for the formal parameter with the default value set. At this time, the function will directly use the default value set during function definition. Of course, you can also replace its default value by explicit assignment. It is optional to pass arguments for the default value parameter when calling the function.
It should be noted that when defining a function with a default value parameter, no ordinary location parameter without a default value can appear on the right of any default value parameter, otherwise a syntax error will be prompted.
The function definition syntax with default value parameters is as follows: def Function name(......,Formal parameter name=Default value): Function body >>> def say( message, times =1 ): print((message+' ') * times) >>> say('hello') hello >>> say('hello', 3) hello hello hello
3.3 key parameters
Key parameters mainly refer to the parameter transfer method when calling the function, which has nothing to do with the function definition. Through the key parameters, the value can be transferred according to the parameter name to clearly specify which value is transferred to which parameter. The order of the actual parameters can be inconsistent with the order of the formal parameters, but it does not affect the transfer result of the parameter value, which avoids the trouble that users need to remember the parameter position and order, and makes the function call and parameter transfer more flexible and convenient.
>>> def demo(a, b, c=5): print(a, b, c) >>> demo(3, 7) 3 7 5 >>> demo(a=7, b=3, c=6) 7 3 6 >>> demo(c=8, a=9, b=0) 9 0 8
3.4 variable length parameters
There are two main forms of variable length parameters: add 1 * or 2 * before the parameter name**
*parameter is used to receive multiple location parameters and put them in a tuple
**parameter receives multiple key parameters and stores them in the dictionary
# *Usage of parameter >>> def demo(*p): print(p) >>> demo(1,2,3) (1, 2, 3) >>> demo(1,2) (1, 2) >>> demo(1,2,3,4,5,6,7) (1, 2, 3, 4, 5, 6, 7) # **Usage of parameter >>> def demo(**p): for item in p.items(): print(item) >>> demo(x=1,y=2,z=3) ('y', 2) ('x', 1) ('z', 3)
3.5 sequence unpacking during parameter transfer
When passing parameters, you can unpack the argument sequence by adding an asterisk before it, and then pass it to multiple univariate formal parameters.
>>> def demo(a, b, c): print(a+b+c) >>> seq = [1, 2, 3] >>> demo(*seq) 6 >>> tup = (1, 2, 3) >>> demo(*tup) 6 >>> dic = {1:'a', 2:'b', 3:'c'} >>> demo(*dic) 6 >>> Set = {1, 2, 3} >>> demo(*Set) 6 >>> demo(*dic.values()) abc
If the function argument is a dictionary, you can unpack it with two asterisks in front, which is equivalent to the key parameter.
>>> def demo(a, b, c): print(a+b+c) >>> dic = {'a':1, 'b':2, 'c':3} >>> demo(**dic) 6 >>> demo(a=1, b=2, c=3) 6 >>> demo(*dic.values()) 6
4. Scope of variable
The code range in which a variable works is called the scope of the variable. Variable names in different scopes can be the same without affecting each other.
Ordinary variables defined inside a function only work inside the function and are called local variables. When the function is executed, the local variable is automatically deleted and can no longer be used.
The reference speed of local variables is faster than that of global variables, which should be given priority.
Global variables can be defined by the keyword global.
There are two situations:
A variable has been defined outside the function. If you need to assign a value to this variable inside the function and want to reflect the assignment result outside the function, you can use global to declare it as a global variable inside the function.
If a variable is not defined outside the function, it can also be directly defined as a global variable inside the function. After the function is executed, a new global variable will be added.
It can also be understood as follows:
Only the value of a variable is referenced in the function without assigning a new value. If such an operation can be performed, the variable is an (implicit) global variable;
If there is an operation to assign a new value to a variable anywhere in the function, the variable is considered to be a (implicit) local variable unless it is explicitly declared with the keyword global in the function.
>>> def demo(): global x x = 3 y = 4 print(x,y) >>> x = 5 >>> demo() 3 4 >>> x 3 >>> y NameError: name 'y' is not defined >>> del x >>> x NameError: name 'x' is not defined >>> demo() 3 4 >>> x 3 >>> y NameError: name 'y' is not defined
If a local variable has the same name as a global variable, the local variable hides the global variable with the same name in its scope.
>>> def demo(): x = 3 #Local variables are created and global variables with the same name are automatically hidden >>> x = 5 >>> x 5 >>> demo() >>> x #Function execution does not affect the value of external global variables 5
5. Lambda expression
lambda expressions can be used to declare anonymous functions, that is, temporary small functions without function names. They are especially suitable for situations where one function needs to be used as another function parameter. You can also define named functions.
A lambda expression can only contain one expression. The calculation result of the expression can be regarded as the return value of the function. Compound statements are not allowed, but other functions can be called in the expression.
>>> f = lambda x, y, z: x+y+z #You can name a lambda expression >>> f(1,2,3) #Call like a function 6 >>> g = lambda x, y=2, z=3: x+y+z #Parameter defaults >>> g(1) 6 >>> g(2, z=4, y=5) #key parameter 11 >>> L = [1,2,3,4,5] >>> print(list(map(lambda x: x+10, L))) #Analog vector operation [11, 12, 13, 14, 15] >>> L [1, 2, 3, 4, 5] >>> data = list(range(20)) #Create list >>> data [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> import random >>> random.shuffle(data) #Disorder order >>> data [4, 3, 11, 13, 12, 15, 9, 2, 10, 6, 19, 18, 14, 8, 0, 7, 5, 17, 1, 16] >>> data.sort(key=lambda x: x) #It has the same effect as non specifying rules >>> data [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> data.sort(key=lambda x: len(str(x))) #Sort by length after conversion to string >>> data [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> data.sort(key=lambda x: len(str(x)), reverse=True) #Descending sort >>> data [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6. Key points of generator function design
A function containing a yield statement can be used to create a generator object. Such a function is also called a generator function.
The yield statement is similar to the return statement in that it is used to return a value from a function. Different from the return statement, the return statement will immediately end the operation of the function once it is executed. Each time it executes the yield statement and returns a value, the execution of the following code will be suspended or suspended. The next time it passes through the generator object__ next__ () method, built-in function next(), for loop traversal of generator object elements or explicitly "ask for" data in other ways.
The generator has the characteristics of inert evaluation and is suitable for big data processing.
# Write and use generator functions that can generate Fibonacci sequences. >>> def f(): a, b = 1, 1 #Unpack the sequence and assign values to multiple elements at the same time while True: yield a #Pause execution and generate a new element if necessary a, b = b, a+b #Unpack the sequence and continue to generate new elements >>> a = f() #Create generator object >>> for i in range(10): #The first 10 elements in Fibonacci sequence print(a.__next__(), end=' ') 1 1 2 3 5 8 13 21 34 55 >>> for i in f(): #The first element in the Fibonacci sequence greater than 100 if i > 100: print(i, end=' ') break 144 >>> a = f() #Create generator object >>> next(a) #Use the built-in function next() to get the elements in the generator object 1 >>> next(a) #Each time a new element is requested, it is generated by the yield statement 1 >>> a.__next__() #You can also call the of the generator object__ next__ () method 2 >>> a.__next__() 3
7. Wonderful case analysis
Write a function to receive string parameters and return a tuple, in which the first element is the number of uppercase letters and the second element is the number of lowercase letters.
def demo(s): result = [0, 0] for ch in s: if ch.islower(): result[1] += 1 elif ch.isupper(): result[0] += 1 return tuple(result)
Write a function, receive an integer t as a parameter, and print the first t line of Yang Hui triangle.
def yanghui(t): print([1]) line = [1, 1] print(line) for i in range(2, t): r = [] for j in range(0, len(line)-1): r.append(line[j]+line[j+1]) line = [1]+r+[1] print(line)
Write a function, receive a positive even number as a parameter, output two prime numbers, and the sum of the two prime numbers is equal to the original positive even number. If there are multiple groups of prime numbers that meet the conditions, all are output.
def demo(n): def IsPrime(p): if p == 2: return True if p%2 == 0: return False for i in range(3, int(p**0.5)+1, 2): if p%i==0: return False return True if isinstance(n, int) and n>0 and n%2==0: for i in range(2, n//2+1): if IsPrime(i) and IsPrime(n-i): print(i, '+', n-i, '=', n)
Write a function to calculate the accuracy of string matching.
Take the typing practice program as an example. Suppose origin is the original content and userInput is the content entered by the user. The following code is used to test the accuracy of user input.
def Rate(origin, userInput): if not (isinstance(origin, str) and isinstance(userInput, str)): print('The two parameters must be strings.') return right = sum((1 for o, u in zip(origin, userInput) if o==u)) return round(right/len(origin), 2)
Write function simulation guessing game. The system randomly generates a number, and the player can guess up to 5 times. The system will prompt according to the player's guess, and the player can adjust the next guess according to the prompt of the system.
from random import randint def guess(maxValue=100, maxTimes=5): #Randomly generate an integer value = randint(1,maxValue) for i in range(maxTimes): prompt = 'Start to GUESS:' if i==0 else 'Guess again:' #Use an exception handling structure to prevent input from being numeric try: x = int(input(prompt)) except: print('Must input an integer between 1 and ', maxValue) else: #You guessed right if x == value: print('Congratulations!') break elif x > value: print('Too big') else: print('Too little') else: #You haven't guessed correctly when you run out of times. The game ends and prompts the correct answer print('Game over. FAIL.') print('The value is ', value) guess()
Implementation of Hanoi Tower Problem Based on recursive algorithm
def hannoi(num, src, dst, temp=None): #Declare the variable used to record the number of moves as a global variable global times #Confirm parameter type and range assert type(num) == int, 'num must be integer' assert num > 0, 'num must > 0' #Only the last or only one plate needs to be moved, which is also the end condition of the recursive call of the function if num == 1: print('The {0} Times move:{1}==>{2}'.format(times, src, dst)) times += 1 else: #Recursively call the function itself, #First move all the plates except the last plate to the temporary column hannuo(num-1, src, temp, dst) #Move the last plate directly to the target post hannuo(1, src, dst) #Move the plates other than the last plate from the temporary column to the target column hannuo(num-1, temp, dst, src) #Variable used to record the number of moves times = 1 #A represents the column where the plate was initially placed, C is the target column, and B is the temporary column hannoi(3, 'A', 'C', 'B')
Write the function and use the algorithm to realize the bubble sorting algorithm
from random import randint def bubbleSort(lst, reverse=False): length = len(lst) for i in range(0, length): flag = False for j in range(0, length-i-1): #Compare the size of two adjacent elements and exchange them as needed. The default is ascending sorting exp = 'lst[j] > lst[j+1]' #If reverse=True, sort in descending order if reverse: exp = 'lst[j] < lst[j+1]' if eval(exp): lst[j], lst[j+1] = lst[j+1], lst[j] #flag=True indicates that element exchange has occurred in this scan flag = True #If there is no element exchange after a scan, it indicates that it has been arranged in order if not flag: break
Write a function to simulate the sorting of selection method
def selectSort(lst, reverse=False): length = len(lst) for i in range(0, length): #Assume the first smallest or largest of the remaining elements m = i #Scan remaining elements for j in range(i+1, length): #If there is a smaller or larger one, record its location exp = 'lst[j] < lst[m]' if reverse: exp = 'lst[j] > lst[m]' if eval(exp): m = j #If smaller or larger values are found, exchange values if m!=i: lst[i], lst[m] = lst[m], lst[i]
Write functions to simulate dichotomy search
def binarySearch(lst, value): start = 0 end = len(lst) while start < end: #Calculate intermediate position middle = (start + end) // 2 #If the search is successful, the corresponding position of the element is returned if value == lst[middle]: return middle #Continue looking in the latter half of the element elif value > lst[middle]: start = middle + 1 #Continue looking in the first half of the element elif value < lst[middle]: end = middle - 1 #If the search is unsuccessful, False is returned return False