while循环:
condition为True,会一直循环while中的语句,直到condition为False
格式:
while [condition]:
. . .
e.g.1
i = 1
while i <= 5:
print('*' * i)
i = i + 1
print("Done")
输出:
D:\Python37\python.exe "D:/pycharm project/myFirstPython.py"
*
**
***
****
*****
Done
Process finished with exit code 0
e.g.2
猜数字游戏,指定一个秘密数字,用户最多猜测3次,如果猜对,显示You Win!,如果猜错,显示Sorry, you failed!
secert_number = 9
guess_number = 0
guess_limit = 3
while guess_number < guess_limit:
guess = int(input('Guess: '))
guess_number +=1
if guess == secert_number:
print("You Win!")
break
else:
print("Sorry, you failed!")