我正在学习python,并开始玩猜谜游戏。我的游戏工作正常,但我的获胜条件打印了“你赢了”和“你输了”,我认为我的"if“语句是不正确的,但我可能是错的。另外,我打印输赢有一个问题,我只能让它打印输赢。提前感谢!
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
number = random.randint(1, 5)
chances = 0
print("Guess a number between 1 and 5:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
if not chances == 0:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
发布于 2020-08-31 09:34:45
试着改变你的循环。如果它是正确的,那么您可以使用while: else
。否则,您可能会在最后一次机会中获胜,但仍然会收到失败的消息。
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
break
win += 1
elif guess < number:
print("Your guess was too low")
else:
print("Your guess was too high")
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
发布于 2020-08-31 09:41:35
在while循环中,if语句应该是...
if guess == number:
print("Something)
win += 1
break
最后一条if语句应该是...
if win != 0:
print("You lose")
else:
print("You win")
发布于 2020-08-31 09:42:15
问题存在于最终的if
语句中。如果玩家的chances
大于diceRoll
,则玩家输了,而如果玩家的机会不是0,即玩家失败了一次,则if条件为真。
最后的if语句的代码应该如下所示:
if chances >= diceRoll:
print("YOU LOSE!!! The number is", number)
loss += 1
至于打印win的问题,这里的问题存在于while循环内的第一个if语句中。如果玩家获胜,则首先遇到break
语句,因此代码将中断while循环,而不会递增win
计数器。
只需将break
语句与win += 1
互换,它将会创造奇迹:
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
break
https://stackoverflow.com/questions/63668207
复制