提示用户输入y、yes、n或n

2024-05-29 00:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要确保所有的条件都得到满足,还有一个特殊情况。即使未满足“2010年之前”或“一般要求”,学生仍被视为“合格”。在

但是,我不能让程序正常工作。我想输入‘y’、‘yes’、‘n’或‘no’来回答‘yes/no’的问题,但是这是一个错误,因为我显然没有指定‘y’。在

^{1}$

Tags: no程序错误情况条件学生yes合格
2条回答

您的完整代码是:

def main():
    credits = int(input("Enter the total number of credits completed: "))
    udcredits = int(input("Enter the number of upper-division credits completed: "))
    localcredits = int(input("Enter the number of local credits completed: "))
    mrequirements = input("Have you completed all major requirements? ")
    before2010 = int(input("In what year did you matriculate? "))
    gerequirements = input("Are your general education requirements done? ")

    if before2010 < 2010 and credits >= 120 and udcredits >= 40 and localcredits >= 30 and mrequirements[0].lower() == 'y':
        print("eligible")
    else:
        print("ineligible")

    if gerequirements[0].lower() == 'y' and credits >= 120 and udcredits >= 40 and localcredits >= 30 and mrequirements[0].lower() == 'y':
        print("eligible")
    else:
        print("ineligible")

main()

变更

  • 第6行,将eval()改为int()这样更安全,更好的实践

  • 第9&14行将.lower()添加到mrequirements[0]gerequirements[0]中,这样即使用户键入大写的Y,测试仍然可以通过。

  • 第9&14行在"y"中添加了引号,因为它保存为Python中input()函数的字符串。否则,if语句将不会返回true

现在应该可以了。在

gerequirements[0] == y

这行代码不能编译。如果要匹配字符y,则必须用引号将其括起来以表示字符串。如果没有引号,Python希望y是一个变量。在

所以表达式变成:

^{pr2}$

正如您提到的其他代码的问题:

  • 首选^{} to ^{}。在
  • Never use ^{},当然不是在用户输入上;在您的例子中,您可能想要^{}。在
  • 您应该lower-case您的yes/no输入允许用户输入大写或小写。在

相关问题 更多 >

    热门问题