首页 > 解决方案 > 我不明白这段代码有什么问题

问题描述

我收到 elif 选项 ==2: 的语法错误。我想知道我需要做什么来修复它。我遵循了教授给我们的伪代码,但它仍然无法运行。我想知道我是否不应该使用 elif 或者可能关于缩进的某些内容已关闭。

import random

print("Welcome to the guess my number program")

while True:
        print("1. You guess the number")
        print("2. You type a number and see if the computer can guess it")
        print("3. Exit")
        option = int(input("Please enter your number here: "))
        if option ==1:
        #generates a random number
                mynumber = random.randint(1,11)
        #number of guesses
        count = 1
        while True:
                try:
                        guess = int(input("Guess a number between 1 and 10:"))
                        while guess < 1 or guess > 10:
                                guess = int(input("Guess a number between 1 and 10:"))  # THIS LINE HERE
                except:
                        print("Numbers Only")
                        continue
                #prints if the number you chose is too low and adds 1 to the counter
                if guess < mynumber:
                        print("The number you chose is too low")
                        count= count+1
                #prints if the number you chose is too high and adds 1 to the counter
                elif guess > mynumber:
                        print("The number you choose is too high")  
                        count = count+1
#If the number you chose is correct it will tell you that you guessed the number and how many attempts it took
                elif guess == mynumber:
                        print("You guessed it in " , count , "attempts")
                        break
        elif option == 2:
                number = int(input("Please Enter a Number: "))
                count = 1
                while True:
                        randomval = random.randint(1,11)
                        if (number < randomval):
                                print("Too high")
                        elif (number > randomval):
                                print("Too low")
                                count = count+1
                        elif (number==randomval):
                                print("The computer guessed it in" + count + "attempts. The number was" + randomval)
                                break
                else:
                        break    

标签: pythonpython-3.x

解决方案


问题很简单。if option == 1和之间没有连续性elif option == 2,因为在 while 循环之间。你所要做的就是删除el部分,elif option == 2然后只写if option == 2.

我自己没有测试过整个程序。但乍一看,这应该可以解决问题。

否则请发表评论。


推荐阅读