例子一:
# Author: Alex Chen real_age = 45 count = 0 while True: if count == 3: break age = int(input("please input age:")) if age == real_age: print("cool, you got it.") break elif age > real_age: print("should be smaller.") else: print("should be bigger.") count += 1
例子二:优化版
# Author: Alex Chen real_age = 45 count = 0 while count < 3: age = int(input("please input age:")) if age == real_age: print("cool, you got it.") break elif age > real_age: print("should be smaller.") else: print("should be bigger.") count += 1
例子三:
# Author: Alex Chen real_age = 45 count = 0 while count < 3: age = int(input("please input age:")) if age == real_age: print("cool, you got it.") break elif age > real_age: print("should be smaller.") else: print("should be bigger.") count += 1 else: print("You have tried too many times, stopped.")
python中可以有while else的语法
例子四:优化版
# Author: Alex Chen real_age = 45 count = 0 while count < 3: age = int(input("please input age:")) if age == real_age: print("cool, you got it.") break elif age > real_age: print("should be smaller.") else: print("should be bigger.") count += 1 if count == 3: confirm = input("do you want to keep guess, please make your choose y/n:") if confirm != "n": count=0 else: print("bye bye.")