我不明白这段代码有什么问题

时间:2018-12-09 16:21:14

标签: python python-3.x

我收到elif选项== 2:的语法错误。我想知道如何解决此问题。我遵循了教授给我们的伪代码,但仍然无法运行。我想知道我是否应该使用省略号,或者有关缩进的信息已关闭。

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    

1 个答案:

答案 0 :(得分:-1)

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

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

否则请发表评论。