【问题标题】:I'm having some Python issues with defining user-input based variables我在定义基于用户输入的变量时遇到了一些 Python 问题
【发布时间】:2020-03-12 16:23:14
【问题描述】:

我知道你以前见过这个,但我真的需要帮助。 我一直在为我的 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!")

【问题讨论】:

  • 每个问题都需要一个单独的if/else。并且打印下一个问题不应该在if 块中。
  • 谢谢!我会这样做并再试一次
  • (1) 将输入转换为数字。 (2) 等式检验是== 运算符。 (3)您可以在此处将除第一个“if”之外的所有内容都替换为“elif”以使其正常工作。
  • @MichaelButscher 实际上elif 在这里不起作用,他需要单独的if/elses
  • 如果除了我当前的问题还有其他问题当前的问题是什么?

标签: python syntax


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    每个if 都需要一个else:,而不是最后一个。问题不应该出现在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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2020-06-12
      • 2019-02-15
      相关资源
      最近更新 更多