简体   繁体   中英

True False Quiz Function in Python

I have created the following program in Python:

def tf_quiz(question, correct_ans):
    if input(question) == correct_ans:
        return("correct")
    else:
        return("incorrect")

quiz_eval = tf_quiz("Birds can fly", "T")

print("your answer is", quiz_eval)

However, my output is as following:

Birds can flyF
your answer is incorrect

But I want the following output:

(T/F) Birds can fly: F
your answer is incorrect

What do I need to change in my code?

Your question is missing a "(T/F) " string at the beginning, and a colon and space at the end.

def tf_quiz(question, correct_ans):
    if input("(T/F) " + question + ": ") == correct_ans:
        return("correct")
    else:
        return("incorrect")

quiz_eval = tf_quiz("Birds can fly", "T")

print("your answer is", quiz_eval)

Either update the question text to have the exact formatting you want:

quiz_eval = tf_quiz("(T/F) Birds can fly: ", "T")

Or update the input() call to insert generic formatting for a true/false question:

if input("(T/F) %s: " % question) == correct_ans:

Change:

if input(question) == correct_ans:

to:

if input(f"(T/F) {question}: ") == correct_ans

if you want the caller to be able to specify each question without the extra formatting pieces.

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