有条件后我的while循环不会停止

时间:2019-10-15 16:34:04

标签: python python-3.x

我做了一个骰子游戏,你有3局,如果你猜不到3局,它会显示数字并说你输了,但对我来说,只有在你没猜到的情况下,它才会显示四分之一。

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

3 个答案:

答案 0 :(得分:3)

一种更简洁的书写方式是

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子句。

答案 1 :(得分:1)

您将使用以下行为用户提供更多机会:pFunc1。尝试改为声明option=int(input("Enter a number between 1 and 6: "))

答案 2 :(得分:1)

您的代码显然会(在循环之前)授予初始猜测,然后在循环内再授予三个猜测。如果您希望它是3个猜测,则只需将猜测计数器减少1。