首页 > 解决方案 > 我的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

标签: pythonpython-3.x

解决方案


写这个的更简洁的方法是

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.


推荐阅读