首页 > 解决方案 > 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!")

标签: pythonpython-3.xerror-handling

解决方案


纠正一些错误后,它看起来像这样:

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!")

推荐阅读