python base 04 control statement

1 Select Structure

1.1 Single Branch

if conditional expression:
Statement/statement block
Conditional expressions: can be logical expressions, relational expressions, arithmetic expressions, and so on.
Statement/statement block: Can be one statement or multiple statements. Indentation must be aligned for multiple statements

The value of a conditional expression is False as follows:
False, 0, 0.0, null value None, empty sequence object (empty list, null ancestor, empty set, empty dictionary, empty string), empty range object, empty iteration object
In a conditional expression, ** cannot have assignment operator'='** replaced with'==''

1.2 Double Branch Structure

if conditional expression:
Statement 1/Statement Block 1
Statement 2/Statement Block 2

Ternary Conditional Operator
For some simple double branch assignments, the format is as follows:

Value when condition is true if (Conditional expression) else Value when condition is false
num = input("Please enter a number")
print( num if int(num)<10 else "Number is too large")

1.3 Multi-Branch Structure

if Conditional expression 1 :
	Statement 1/Statement block 1
elif Conditional expression 2:
	Statement 2/Statement block 2
elif Conditional expression n :
	Sentence n/Statement block n
	Sentence n+1/Statement block n+1

1.4 Selection structure nesting

Example: Enter a score. The score is between 0 and 100. Above 90 is A, above 80 is B, above 70 is C, 60
Above is D. Below 60 is E.

The method code is more concise;
score = int(input("Please enter a 0-100 Number:"))
degree = "ABCDE"
num = 0
if score >100 and score <0:
	score = int(input("Re-enter:"))
	num =  score // 10
	if num <6:num = 5
	print('Score is{0},Level is{1}'.format(score,degree[9-num]))

2 Cycle structure

2.1 while Loop

while Conditional expression:
	Loop body statement

2.2 for loop

for variable in Iterable objects:
	Loop body statement
d = {'name':'gao'}
for i in d.keys(): #Walk through all key s in the dictionary
for i in d.values():
	print(i) #Traverse through all the values in the dictionary
for i in d.items():
	print(i) # Traverse through all key-value pairs in a dictionary

Python contains the following iterative objects:
1.Contains: string, list, tuple
3.iterator object
4.generator function
5.File object

2.3 break and continue statements

1 break
Can be used in while and for loops to end the entire loop. When there are nested loops, break jumps out of the last level of loop.

while True:
	a = input("Please enter a character (enter) Q or q End)")
	if a.upper()=='Q':
		print("End of loop, exit")

2 continue statement
When multiple loops are nested, continue is also applied to the nearest loop.

Require employee's salary to be entered and re-enter if the salary is less than 0. Final print out the number of employees and
Pay details, and average salary

empNum = 0
salarySum= 0
salarys = []
while True:
    s = input("Please enter the employee's salary (press Q or q End)")
    if s.upper()=='Q':
        print("Entry complete, exit")
    if float(s)<0:
    empNum +=1
    salarySum += float(s)
print("Number of employees{0}".format(empNum))
print("Enter salary:",salarys)
print("Average Salary{0}".format(salarySum/empNum))

2.4 else statement

An else statement can be added to a loop statement. If the loop is not ended by a break, the else statement is executed, otherwise it is not executed. The format is:

while Conditional expression:
	Circulatory body
for variable in Iterable objects:
	Circulatory body
	Statement block

There are 4 employees in total. The salaries of these 4 employees are entered. After all entries, print out the prompt "You have already entered the salaries of all 4 employees". Finally, print out the entered salaries and average salaries.

salarySum= 0
salarys = []
for i in range(4):
	s = input("Please enter the salary for a total of 4 employees (press Q or q End halfway)")
	if s.upper()=='Q':
		print("Entry complete, exit")
	if float(s)<0:
	salarySum += float(s)
	print("You've entered all four employees'salaries")
	print("Enter salary:",salarys)
	print("Average Salary{0}".format(salarySum/4))

2.5 Cycle optimization - a must-have for a master

Complying with the following three principles can greatly improve operational efficiency and avoid unnecessary inefficient calculations:
1. Minimize unnecessary calculations within the loop
2. In nested loops, minimize the calculation of inner loops and pull outward whenever possible
3. Query local variables quickly, try to use local variables

import time
start = time.time()
for i in range(1000):
	result = []
	for m in range(10000):
end = time.time()
print("Time consuming:{0}".format((end-start)))

start2 = time.time()
for i in range(1000):
	result = []
	c = i*1000  Calculate pull outward
	for m in range(10000):
end2 = time.time()
print("Time consuming:{0}".format((end2-start2)))

Other optimization methods:
When splicing strings, use join() instead of +
Insert and delete elements from the list, as far as possible at the end of the list

2.3 Parallel iteration using zip()

Multiple sequences can be iterated in parallel through the zip() function, which stops when the shortest sequence "runs out"

names = ("High Cream","Sophomore","Senior Three","Senior Four")
ages = (18,16,20,25)
jobs = ("Teacher","Programmer","Civil servant")
for name,age,job in zip(names,ages,jobs):

Execution results:
Gao Qi - 18 - Teacher
Sophomore - 16 - Programmer
Senior Three-20-Civil Servant
The same effect:

for i in range(3):

3 Derivative Creation Sequence

3.1 List Derivation

[Expression for item in Iterable Objects]perhaps
[Expression for item in Iterable Objects if Conditional Judgment]
>>>[x for x in range(1,5)]
>>>[a for a in 'abcde']
>>>[(a,b) for a in range(4) for b in range(4)] #There are two loops available

3.2 Dictionary Derivation

{key_expressiom:value_expression for Expression in Iterable Objects} #You can also add if condition judgment, multiple for loops
 Count the number of occurrences of characters in the text:
>>> my_text = ' i love you, i love sxt, i love gaoqi' 
>>>> char_count = {c:my_text.count(c) for c in my_text

3.3 Set Derivation

{Expression for item in Iterable Objects}perhaps
{Expression for item in Iterable Objects if Conditional Judgment}

3.4 Generator Push-to-Push (Generate Tuples)

 (x for x in range(1,100) if x % 9 == 0)
 Generate an iterator:
 <generator object <genexpr> at 0x00000241CF012C80>

An iterator can only run once, the first iteration yields data, the second iteration has no data

Tags: Python

Posted on Sun, 03 Oct 2021 14:04:50 -0400 by zipp