0

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
  • 2
    ...you're asking how to compare a variable to the empty string? Really? – Aran-Fey Apr 05 '18 at 21:16
  • 1
    Possible duplicate of [Most elegant way to check if the string is empty in Python?](https://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python) – Aran-Fey Apr 05 '18 at 21:16

1 Answers1

3

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.

Azsgy
  • 3,139
  • 2
  • 29
  • 40
  • Thanks very much - that worked out. Though I was wondering where I would add that user_answer.strip into the code? – Nathan Godfrey Apr 05 '18 at 21:21
  • I think you should add it directly after getting the input. That way, whitespace at the start and end will be ignored for all parts of the program – Azsgy Apr 05 '18 at 21:22