Python程序循环



有人可以看看我的代码,看看为什么我得到第41行语法错误,请?"这是一个让用户选择猜数字的程序在游戏中,玩家可以选择在1到100之间进行无限猜测5的猜测。"

menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None

设置循环

while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
count = count+1
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
count = count+1
elif (guess == x):
print ("Congratulations, you guessed the number in", count,
"attempts!")
elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:")
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!)
if (guess == x):
print ("You won!")
else:
print ("You lost!")
elif (guess == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")

修正了一些错误后,它看起来是这样的:

import random
menu = """
1. Play Game unlimited guesses
2. Play Game with 5 guesses
0. Exit
"""
choice = None
while (choice != 0):
print (menu)
gameCode = int(input("Would you like to play a game?"))
if (gameCode == 1):
count=0
print ("Guess a number between 1 & 100:")
x = random.randint (1, 100)
guess = int(input())
while (guess != x):
count = count+1
if (guess < x):
guess = int(input("Your guess is too low, try again:"))
elif (guess > x):
guess = int(input("Your guess is too high, try again:"))
print(f"Congratulations, you guessed the number in {count} attempts!")

elif (gameCode == 2):
for i in range (1,6,1):
guess = int(input("Enter a guess between 1 and 100:"))
if (guess == x):
print ("You got it!")
else:
print ("Sorry, incorrect!")
elif (gameCode == 0):
break
else:
print ("You entered an invalid game code. Goodbye!")

最新更新