It is often used to traverse strings 、 list 、 Tuples 、 Dictionaries 、 Set and other sequence types , Get the elements of the sequence one by one ,python Medium for The loop needs to specify the scope of the iteration .
His format is usually :
for Variable in character string | list | Tuples | Dictionaries | aggregate :
for example : seek 1~100 and
sum=0
for i in range(1,101)
sum +=i
print(sum)
User login program
1. Enter your username and password
2. Determine whether the user name and password are correct ('name==root','passwd='123')
3. In order to prevent violent cracking , There are only three logins , If you have more than three chances , Report errors
About ending a cycle , There are several ways
break Out of the loop The contents after the loop will not be executed
break Statement used in while and for In circulation , If you use nested loops ,break Statement will stop executing the deepest loop , And start executing the next line of code
continue Jump out of this cycle ,continue The following code content will not be executed
exit() End the whole program
pass Do nothing , It only plays a space occupying role
while The grammatical structure of a loop is :
while Judgment statement , Execute statement
He and for The difference between cycles is :for The loop needs to add an iterative object or range , and while Circulation does not ;
This is the user name and password above , Switch to while The loop method completes ;
i=0
while i <3:
name = input (" user name :")
passward=input(“ password :”)
if name==“root”and passward==“123”:
print(“ Login successful ”)
break
else:
print(“ Login failed ”)
print(“ You still have %d Second chance ”%(2-i)))
i+=1
else:
print(" Log in more than 3 Please wait 100s Try again later !!!")
One 、 Algorithm 1. Definition