appreciationsociety
appreciationsociety

Reputation: 1

Try and Except statements

I'm wondering how to make this code flag up 'not a word' if the user types numbers as the answer to this question

question=input("What is the capital of England? ")
question=question.lower()

if question==(""):
    print("Empty value")
else:
    try:
        str(question)
    except:
        print("Not a word!")
    else:
        if question==("london"):
            print ("Correct")
        else:
            print ("Wrong")

Upvotes: 0

Views: 76

Answers (1)

HavelTheGreat
HavelTheGreat

Reputation: 3386

You have some syntax errors, but there's no real need for a try-except here for your intents and purposes because all input received from the user is already a string. str(question) will work in nearly any case. You could simply use .isalpha() to restrict the input to alpha characters, and an if-elif-else:

if question==(""):
    print("Empty value")
else:
    if not question.isalpha():
        print("Not a word!")
    elif question == "london":
        print("Correct")
    else:
        print("Wrong")

Upvotes: 1

Related Questions