Python-while loop and for loop
1. The while cycle of a cycle
-
Syntax and basic use of loops
while condition: Code 1 Code 2 Code 3
Steps to run while:
**Step 1:** If the condition is true, execute in sequence: Code 1, Code 2, Code 3,...
**Step 2:**After execution, judge the condition again, if the condition is True, execute again: code 1, code 2, code 3,..., if the condition is False, the loop terminates.count=0 while count < 5: print(count) # 0,1,2,3,4 count+=1
-
Dead Cycle and Efficiency
count = 0 while count < 5: print(count) # 0......
while True: name = input('your name >>>> ') print(name)
#Dead cycles with pure computation and no io can cause fatal efficiency problems while 1: # 1 is True 1+1
-
Application of loops
username = 'python' password = '123' tag = True while tag: inp_name = input('Please enter your account number:') inp_pwd = input('Please enter your password:') if inp_name == username and inp_pwd == password: print('Login Successful') tag = False # Later code will run until the next loop determines the condition else: print('Account name or password error') print('====end====')
-
Two ways to exit the loop
a. Conditions: Change condition to false
For example, the example code in "3. Application of Loop" changes the condition to False, and will not take effect until the next time the condition is determined by the loop.
b. while + break
Running to break immediately terminates the layer loop.
username = 'python' password = '123' while True: inp_name = input('Please enter your account number:') inp_pwd = input('Please enter your password:') if inp_name == username and inp_pwd == password: print('Login Successful') break # The layer loop is terminated immediately from here, and the program behind it is no longer executed within the loop, so the last'====end======'is not visible. else: print('Account name or password error') print('====end====')
-
while loop nesting
#Jump out of cycle by condition tag = True while tag: while tag: while tag: tag = False # By breaking out of a loop, each layer must have a break while True: while True: while True: break break break
How to change the condition:
username = 'python' password = '123' tag = True while tag: inp_name = input('Please enter your account number:') inp_pwd = input('Please enter your password:') if inp_name == username and inp_pwd == password: print('Login Successful') while tag: cmd = input("Input Command>: ") if cmd == 'q': tag = False else: print('command{x}Running'.format(x=cmd)) else: print('Account name or password error')
How to break:
username = 'python' password = '123' while True: inp_name = input('Please enter your account number:') inp_pwd = input('Please enter your password:') if inp_name == username and inp_pwd == password: print('Login Successful') while True: cmd = input("Input Command>: ") if cmd == 'q': break print('command{x}Running'.format(x=cmd)) break # Terminate layer loops immediately else: print('Account name or password error')
-
while+continue
End this cycle and go directly to the next one.
Emphasis: It is pointless to add peer code after continue because it will never run.
#Print 0, 1, 2, 3, 5 count=0 while count < 6: if count == 4: count+=1 continue # count+=1 # error print(count) count+=1
-
while+else
while True: ... else: print('else The code contained in the while After the cycle ends, and while The cycle is not break In case of interruption, the normal end will run.')
count = 0 while count < 6: if count == 4: count += 1 continue print(count) count += 1 else: print('Python is my friend') # 0 # 1 # 2 # 3 # 5 # Python is my friend
count=0 while count < 6: if count == 4: break print(count) count += 1 else: print('======>') # 0 # 1 # 2 # 3
It can be said that else in while + else is for break.
2. for loop
In theory, for loops can do everything while loops can do. The reason for loops is that for loops are simpler in value (traversal) than while loops.
-
Syntax for loop
Grammar:
for Variable Name in Iterable Objects: # Iterable objects can be lists, dictionaries, strings, tuples, collections Code 1 Code 2 Code 3 ...
-
for loop basic use
(1) for basic use of circular value
Case 1: List Loop Value
# Simple Edition l = ['Zhang San', 'Li Si', 'King Five'] for x in l: print(x)
# Complex Edition: l = ['Zhang San', 'Li Si', 'King Five'] i = 0 while i < 3: print(l[i]) i += 1
Case 2: Dictionary looping
# Simple Edition dic = {'k1': 111, 'k2': 2222, 'k3': 333} for k in dic: print(k,':',dic[k])
# Complex Edition: A while loop can iterate through a dictionary, but it's too cumbersome
Case 3: String Loop Value
# Simple Edition msg = "you can you up,no can no bb" for x in msg: print(x)
# Complex Edition: A while loop can traverse strings, but it's too cumbersome
(2) The similarities and differences between for loop and while loop
a. The same thing: they are all loops. for loops can do things, while loops can also do things.
b. Differences:
A while loop is called a conditional loop, and the number of cycles depends on when the condition becomes false.
for loops are called "value loops", and the number of loops depends on the number of values that an in-iterated object can contain.(3) for loop control cycle number: range()
There is a limitation to placing a data type directly after in to control the number of loops: when there are too many loops, the format of the data type containing the values needs to increase.
range(10) # 0...9 # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(1,9) # 1...8 # [1, 2, 3, 4, 5, 6, 7, 8] #The third parameter is the step, not written to default to 1. range(1,9,1) # 1 2 3 4 5 6 7 8 # [1, 2, 3, 4, 5, 6, 7, 8] range(1,9,2) # 1 3 5 7 # [1, 3, 5, 7]
(4) range supplementary knowledge
# 1. for with range, it can be indexed, but it is cumbersome, so it is not recommended l = ['aaa', 'bbb', 'ccc'] # len(l) for i in range(len(l)): print(i, l[i]) for x in l: print(l)
# 2. In python3, range() gets an "old hen that lays eggs". In Python 2, space of corresponding size will be opened up according to the data in range, but python3 is optimized to occupy only the size space of its own function.
-
for loop nesting
The outer cycle is once, and the inner cycle needs to be completed completely.
for i in range(2): print('Outer cycle-->', i) for j in range(3): print('Inner Layer-->', j) # Outer loop --> 0 # Inner layer--> 0 # Inner layer --> 1 # Inner layer --> 2 # Outer loop --> 1 # Inner layer--> 0 # Inner layer --> 1 # Inner layer --> 2
-
for+break
Like the while loop, and terminating the for loop has only one break scheme
-
for+continue
for i in range(6): # 0 1 2 3 4 5 if i == 4: continue # End this cycle and go straight to the next start print(i) # 0 1 2 3 5
-
for+else
Same as the while loop