【问题标题】:My input in if statement is not working as expected我在 if 语句中的输入没有按预期工作
【发布时间】:2020-10-01 10:14:15
【问题描述】:

我在 if 语句中的输入不起作用。我正在使用 Python3,问题出在定义函数中的第一个 if 语句。

import random

random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []


def ex():
    proceed = input("Proceed?: ")
    if proceed.lower == "yes":
        ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
        if int(ans) == correct:
            print("Correct!")
            list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
            print(ex())
        else:
            print("Incorrect!")
            list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
    elif proceed.lower == "mfm":
        print(list_of_correct)
        print(list_of_wrong)


print(ex())

【问题讨论】:

    标签: python python-3.x if-statement input


    【解决方案1】:

    固定代码

    import random
    
    random1 = random.randint(1, 11)
    random2 = random.randint(1, 11)
    correct = random1 * random2
    list_of_correct = []
    list_of_wrong = []
    
    
    def ex():
        proceed = input("Proceed?: ")
        if proceed.lower() == "yes":
            ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
            if int(ans) == correct:
                print("Correct!")
                list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
                print(ex())
            else:
                print("Incorrect!")
                list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
        elif proceed.lower() == "mfm":
            print(list_of_correct)
            print(list_of_wrong)
    
    
    print(ex())
    

    【讨论】:

    • 更新了一个错字。 @wjandrea。
    【解决方案2】:

    您将函数 proceed.lower 与字符串 'yes' 进行比较 - 它们永远不会相同。

    你需要调用函数:

    if proceed.lower() == "yes":
    

    将您的输入转换为小写以供比较。

    print("".lower) # <built-in method lower of str object at 0x7fc134277508>
    

    【讨论】:

      猜你喜欢
      • 2017-06-18
      • 2011-11-29
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 2022-11-20
      • 1970-01-01
      相关资源
      最近更新 更多