python - 我的while循环不会在条件后停止
问题描述
我做了一个骰子游戏,你有 3 次,如果你没有猜到 3 次,它会显示数字并说你输了,但对我来说,它只有在你没有猜到 4 次时才会显示去。
import random
import time
guess=3
print ("Welcome to the dice game :) ")
print ("You have 3 guess's all together!")
time.sleep(1)
dice=random.randint(1, 6)
option=int(input("Enter a number between 1 and 6: "))
while option != dice and guess > 0:
option=int(input("Wrong try again you still have " + str(guess) + " chances remaining: "))
guess=guess-1
if guess == 0:
print ("You lost")
print ("The number was " + str(dice))
if option == dice:
print ("You win and got it with " + str(guess) + " guess remaining")
结果是:
Welcome to the dice game :)
You have 3 guess's all together!
Enter a number between 1 and 6: 4
Wrong try again you still have 3 chances remaining: 4
Wrong try again you still have 2 chances remaining: 4
Wrong try again you still have 1 chances remaining: 4
You lost
The number was 2
解决方案
写这个的更简洁的方法是
import random
import time
guesses = 3
print("Welcome to the dice game :) ")
print("You have 3 guesses all together!")
time.sleep(1)
dice = random.randint(1, 6)
while guesses > 0:
option = int(input("Enter a number between 1 and 6: "))
guesses -= 1
if option == dice:
print(f"You win and got it with {guesses} guess(es) remaining")
break
if guesses > 0:
print("Wrong try again you still have {guesses} guess(es) remaining")
else:
print("You lost")
print(f"The number was {dice}")
循环条件仅跟踪剩余的猜测次数。如果您猜对了,请使用显式break
退出循环。else
那么,只有在不使用显式break
.
推荐阅读
- css - 使用我自己的自定义列表中的随机渐变作为背景( SCSS )
- html - 为什么“margin:0 auto”会删除我的div中的空白?如何将 div 与它的空白居中?
- react-native - 如何写下面的代码组件didmount代码在使用效果?
- powershell - 如何使用 PowerShell 在文件名中连续添加数字?
- python-3.x - Heroku CLI 在 pycharm 终端中不起作用
- python - 正则表达式模式重叠的重复文本
- python - 在 Flask 中为 Preflight 请求配置特定标头
- java - 使用java分区负正不与0比较
- redux - Redux Toolkit - 重置状态
- python - 想知道为什么 scipy.spatial.distance.sqeuclidean 比 numpy.sum((y1-y2)**2) 慢两倍