The Road to python-Basics 2
10. If else process judgment
Example 1:
Import getpass # refers to the module getpass _ username = "kk" _ password = "123456" username = input ("username:") password = getpass.getpass ("password") # getpass function is to make the password not directly displayed in plaintext if _ username = = username and _ password = = password: print ("Welcome user {name} login..." .format (name = username)) # print ("Welcome user% s login..."% username) else: print ("error")
Note: indent function: subcode needs to be indented
Example 2:
# guess age age_of_oldboy = 65guess_age = int (input ("guess age:") if guess_age = = age_of_oldboy: print ("Yes, you got it.") elif guess_age > age_of_oldboy: print ("No,think bigger!") else: print ("No,think smaller!")
11. While cycle
Example 1:
# endless loop count = 0while True: print ("count", count) count = count + 1
Example 2:
Age_of_oldboy = 65 count = 0 # set count while count
< 3:#如果小于3次时循环执行 #if count == 3: #break guess_age = int(input("guess age:")) if guess_age == age_of_oldboy: print("Yes, you got it.") break elif guess_age >Age_of_oldboy: print ("No, think bigger!") Else: print ("No,think smaller!") Count + = 1else: print ("Funk off")
Example 3:
# cycle to guess the age, and the end prompt whether to continue guessing
Age_of_oldboy = 65count = 0while count
< 3:# if count == 3:# break guess_age = int(input("guess age:")) if guess_age == age_of_oldboy: print("Yes, you got it.") break elif guess_age >Age_of_oldboy: print ("No, think bigger!") Else: print ("No,think smaller!") Count + = 1 if count = = 3 if count # guessed three times before asking the user whether to continue guessing coutine_confim = input ("do you want to keep guessing?:") if coutine_confim! = "n": count = 0#else:# this does not need # print ("Funk off")
Note:
Continue: jump out of this cycle and continue to the next cycle
Break: end the entire cycle
12. For cycle
Example 1:
# for loop for i in range (10): print ("loop", I)
Answer: C:\ Users\ Documents\ python > python learn01.pyloop 0loop 1loop 2loop 3loop 4loop 5loop 6loop 7loop 8loop 9
Example 2:
# cyclic age guessing
Age_of_oldboy = 65for i in range (3): guess_age = int (input ("guess age:")) if guess_age = = age_of_oldboy: print ("Yes, you got it.") Break elif guess_age > age_of_oldboy: print ("No, think bigger!") Else: print ("No,think smaller!") else: print ("Funk off")
Example 3:
For i in range (0Jing 10jue 2): print ("loop", I)
Examples 4:
# the big loop I executes once, and the small loop executes for i in range (10): print ('-', I) for j in range (10): print (j) if j > 5. If the small loop is greater than 5, stop break