简体   繁体   中英

Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?

I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,

if guess.isdigit():
     guess = int(guess)

Please help

import random 
a = random.randint(1,10)

print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")

if question_one == "Yes":
    print("Let's go!")
else:
    print("That sucks!")
    exit()
guess = None
while guess != a:
    guess = (input("Alright, guess a number from 1-10"))
    if guess.isdigit():
        guess = int(guess)

    if guess > a:
        guess = int(input("Guess lower!"))
    elif guess < a:
        guess = int(input("Guess higher!"))
    else guess == a:
        print("you got it!")

else doesn't let you define a condition. else will execute if all other conditionals return false. You should change that last else to elif . Or you can simply leave out the conditional guess == a all together. If it is not greater than or less than, the only other thing it can be is equal to.

If you have the last else, the code inside the else will be executed if any other condition goes false. So I think if you change the last else with an elif we work properly.

An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:

elif guess == a:
        print("you got it!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM