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
Python strings are "falsy" when empty. This means that when converted to a bool, eg 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.
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.