我在定义基于用户输入的变量时遇到一些Python问题

问题描述 投票:-1回答:2

我知道您以前已经看过,但是我确实需要这里的帮助。我一直在为Tech Ed创建一个基于Python的“数学测试”程序。类,我一直在努力用数字形式正确定义答案,以下是我的低于标准的Python脚本。如果除了我当前的问题以外还有其他问题,请告诉我。下面是引起问题的源代码。

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!")
python syntax
2个回答
0
投票

[input返回str,如果您希望python将其视为整数,请执行以下操作:

answer = int(input())

而且,您的代码现在的工作方式将是第三个问题的所有三个答案。如果每个问题的答案有误,您都需要一个单独的else,例如:

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

这样,每个问题只有一个正确答案。


0
投票

每个else:需要一个if,而不仅仅是结尾处的一个。而且问题不应该出现在if中–您的操作方式是根据下一个结果检查上一个问题的答案。另外,如果比较应使用==。

而且您必须要求输入每个问题,并将其转换为整数。

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")

为了避免所有这些重复,您可能希望列出问题和答案,并使用循环。

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")
© www.soinside.com 2019 - 2024. All rights reserved.