Python 我的while循环赢了';有条件后不要停止
我做了一个骰子游戏,你有3个棋子,如果你在3个棋子中猜不到,它会告诉你数字并说你输了,但对我来说,只有在你在4个棋子中猜不到的情况下,它才会显示出来Python 我的while循环赢了';有条件后不要停止,python,python-3.x,Python,Python 3.x,我做了一个骰子游戏,你有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(inpu
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
这一行为用户提供了额外的机会:
option=int(输入(“输入一个介于1和6之间的数字”)
。请尝试声明guess=2
。您的代码明确授予初始猜测(在循环之前),然后再授予三个猜测(在循环内)。如果您希望它是3次猜测,那么只需将猜测计数器减少1。写这篇文章的更简洁的方法是
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}")
循环条件只跟踪剩余的猜测次数。如果猜测正确,请使用显式的
中断
退出循环。循环中的else
子句只有在您没有使用显式的break
时才会执行。您是否已设法确定程序的哪一部分工作正常?您是否尝试过打印变量以显示发生了什么?您是否用纸和笔浏览了代码,试图诊断问题?我认为,如果您的程序输出与原始程序不一样,您不能简单地称之为更干净的实现。您没有正确地通知用户他的输入是错误的,您也没有通知用户他还剩多少次尝试。我认为这是OP面临的问题的一部分,他希望在第一次尝试时得到不同的消息,然后重试,然后OP弄乱了它们的计数器变量。所以我认为你只是删掉了对初学者来说“更难”的部分,用一种“干净”的方式来写。这很容易修复。太好了。期待你改进的答案。届时我们将投票表决。