Python can limit the number of guesses about age by using while and for loops
1. In the small program of guessing age, the code without loop is as follows:
age_of_yu = 23 guess_age = int(input("guess_age:")) if guess_age == age_of_yu: print("you got it!") elif guess_age > age_of_yu: print("think smaller...") else: print("think bigger...")
#Here, int (input ("guess? Age:") is to cast the default data type (str) defined by variable into int type, so that conditional comparison of if can be performed
2. The number of times to guess age through for cycle is 3
age_of_yu = 23 for i in range(3): guess_age = int(input("guess_age:")) if guess_age == age_of_yu: print("you got it!") break elif guess_age > age_of_yu: print("think smaller...") else: print("think bigger...") else: print("you have tried too many times!")
3. The number of times to guess age through the while cycle is 3
age_of_yu = 23 count = 0 while count < 3: guess_age = int(input("guess_age:")) if guess_age == age_of_yu: print("you got it!") break elif guess_age > age_of_yu: print("think smaller...") else: print("think bigger...") count += 1 else: print("you have tried too many times!")
4. Guess age, ask to guess whether to continue to guess after three times of asking. If you enter "n", it means to continue to guess, otherwise it means not to continue
age_of_yu = 23 count = 0 while count < 3: guess_age = int(input("guess_age:")) if guess_age == age_of_yu: print("you got it!") break elif guess_age > age_of_yu: print("think smaller...") else: print("think bigger...") count += 1 if count == 3: continue_guess = input("Do you want to go on guessing ?(input n End, enter any other key to continue...)") if continue_guess != 'n': count = 0 else: print("guessing end...")