简体   繁体   中英

I'm having some Python issues with defining user-input based variables

I know you've seen this before, but I really need help here. I've been creating a Python based "math testing" program for my Tech Ed. class, and I've been struggling with properly defining the answers in numeric form, below is my sub-par Python script. If there are any other issues besides my current issue, please let me know. Below is the source code causing the issue.

print("e = 16 , a = 6 | a*10-e ")
answer = input()

if answer = 44:
    print("You got it!")
    print(" n = 186 | 4+n/2")
if answer = 97:
    print("You got it!")
    print(" a = 4 , b = 6 | b^(2)-a")
if answer = 32:
    print(" you got it!")
else:
 print("Sorry, thats incorrect")
 print("please restart the test!")

input returns a str , if you want python to treat it as an integer do:

answer = int(input())

Also, the way your code works right now all three answers will be accepted for the first question. You need an individual else for each question in case its answer is wrong, something like:

if answer == 44:  # Note '==' and not '='
    print("You got it!")
else:
     print("Sorry, thats incorrect")
     print("please restart the test!")
print(" n = 186 | 4+n/2")
# The same for the rest of the questions

That way there's only one correct answer for every question.

You need an else: for each if , not just one at the end. And the questions should not be in the if -- the way you did it you check the answer to the previous question against the next result. Also if comparisons should use == .

And you have to ask for input for each question, and convert it to integer.

print("e = 16 , a = 6 | a*10-e ")
answer = int(input())
if answer == 44:
    print("You got it!")
else:
    print("Sorry, thats incorrect")

print(" n = 186 | 4+n/2")
answer = int(input())
if answer == 97:
    print("You got it!")
else:
    print("Sorry, thats incorrect")

print(" a = 4 , b = 6 | b^(2)-a")
answer = int(input())
if answer == 32:
    print(" you got it!")
else:
    print("Sorry, thats incorrect")

To avoid all this duplication, you might want to make a list of questions and answers, and use a loop.

questions = (("e = 16 , a = 6 | a*10-e ", 44),
             (" n = 186 | 4+n/2", 97),
             ("a = 4 , b = 6 | b^(2)-a", 32))
for question, answer in questions:
    response = int(input(question))
    if answer == response:
        print("you got it!")
    else:
        print("Sorry, that's incorrect")

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