我试图在我的猜谜游戏中添加一个Doyouwantoplayear功能,但它停止了工作:(请帮助。我对python非常陌生,所以我打赌我犯了很多不经意的错误:S
import random
n = random.randint(1, 100)
play_game = input("Do you want to play ? Y/N :")
play_game = play_game.upper()
print("play_game")
while play_game == 'Y':
guess = int(input("Guess a number between 1 och 100: "))
while n != "gissning":
if guess < n:
print("You guessed to low")
guess = int(input("Guess a number between 1 och 100: "))
elif guess > n:
print ("You guessed to high")
guess = int(input("Guess a number between 1 och 100: "))
else:
print("Gratz you guessed it")
break
while play_game == 'Y':
# your game
play_game = input("Do you want to play again? Y/N :").upper()
事实上,代码中有一些小问题,但是通过一些逻辑,您可以解决它
首先,您不需要三个分开的
while
循环,因为当您退出其中一个循环时,除非重新启动代码,否则您将永远无法再次访问它。实际上,您需要嵌套循环。外部的一个将验证用户是否想再次玩,而内部的一个将继续猜测,直到它匹配随机数第二,您希望将
n
随机数与guess
用户输入进行比较。在代码中,您正在比较n != "gissning"
,这永远不会是真的,因为n
是一个数字"gissning"
是一个字符串考虑到这一点,您可以稍微更改代码,并实现如下功能:
希望这对你有所帮助。祝你旅途好运!如果您还有任何问题,请告诉我们
下一个输入提示应该在外部while循环中。当已经是n==guess时,还需要打印“Gratz You guess it”以及提示,并在内部while循环外部打印
相关问题 更多 >
编程相关推荐