提示用户输入y,yes,n或no

时间:2015-07-21 02:34:50

标签: python user-input

我需要确保满足所有条件,特殊情况。该学生仍被视为符合条件的#39;即使是2010年之前的''或者' gerequirements'没有遇见。

但是,我无法让程序正常运行。我希望能够输入'是,'是',' n'或者' no'对于是/否问题的答案,但它是一个错误,因为我没有指定' y'显然。

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 = eval(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] == y:
        print("eligible")
    else:
        print("ineligible")

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

2 个答案:

答案 0 :(得分:4)

gerequirements[0] == y

这一行不会编译。如果您尝试匹配字符y,则必须将其用引号括起来表示字符串。如果没有引号,Python希望y是一个变量。

因此表达式变为:

gerequirements[0] == 'y'

正如评论者提到的那样,您的代码存在其他几个问题:

答案 1 :(得分: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行&amp; 14将.lower()添加到 mrequirements [0] gerequirements [0] ,这样即使用户输入大写字母Y,测试woud仍然会通过。

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

它现在应该运行良好。