Python3.7 初识循环
While 条件:
条件为真(True)执行的操作
非常简洁
猜数字游戏:
import random //导入外部模块random temp = input('Guess the integer: ') secret = random.randint(1,10) //调用random中的randint()函数 guess = int(temp) while guess != secret: if guess > secret: print('too big!') else: print('too small!') temp = input('Try again plz: ') guess = int(temp) print('Bingo!!') print('Bye~')
F5看效果:
>>> Guess the integer: 9 too big! Try again plz: 5 Bingo!! Bye~ >>>
这个游戏只有猜对了才能退出,不够人性化,改进一下:
import random temp = input('Guess the integer: ') secret = random.randint(1,10) guess = int(temp) times = 1 while (guess != secret) and (times < 3): if guess > secret: print('too big!') else: print('too small!') temp = input('Try again plz: ') guess = int(temp) times += 1 if (times <= 3) and (guess == secret): print('Bingo!!') print('Bye~') else: print('Run out of times~')
运行效果:
>>> Guess the integer: 1 too small! Try again plz: 2 too small! Try again plz: 3 Run out of times~ >>>
本文来自博客园,作者:巴拉拉没多少能量,转载请注明原文链接:https://www.cnblogs.com/beishi/p/15744162.html