Nathan Godfrey
Nathan Godfrey

Reputation: 9

How to recognise a blank input in a Python quiz

I've got this quiz set up with part of the code below and the quiz works fine and there's a score function that give +2 if correct and -2 if wrong but I wanted to also give -1 if it was left blank. How would I be able to do this?

for q in questions.keys():
    user_answer = input(q)
    if questions.get(q) == str(user_answer):
        score += 2
    else:
        score -=2

Upvotes: 0

Views: 90

Answers (1)

Azsgy
Azsgy

Reputation: 3307

Python strings are "falsy" when empty. This means that when converted to a bool, e.g. by the if statement, they will return False, while non-empty strings will return True. This means you can just use

if not user_answer:
    score += 1

to check.

It is a good idea to also use user_answer.strip() to remove any whitespace around the string.

Upvotes: 3

Related Questions