我需要确保满足所有条件,但有一个特殊情况。即使不符合"2010年以前"或"一般要求",该学生仍被视为"合格"。
然而,我不能使程序正常工作。我希望能够输入'y', 'yes', '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()
gerequirements[0] == y
这一行将无法编译。如果您试图匹配字符y
,则必须将其括在引号中以表示字符串。如果没有引号,Python期望y
是一个变量。
所以表达式变成了:
gerequirements[0] == 'y'
正如评论者所提到的,您的代码还有其他几个问题:
- 优先选择
raw_input
而不是input
。 - 永远不要使用
eval
,当然不是用户输入;在你的情况下,你可能需要int()
。 - 你应该小写你的yes/no输入,以允许用户输入大写或小写。
你的完整代码应该是:
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在mrequirements[0]和 gerrequirements [0]中增加了
.lower()
,这样即使用户输入大写Y,测试仍然通过。- 第9行&14为
"y"
添加引号,因为它被保存为Python中input()函数的字符串。否则if
语句不会返回true
应该可以正常运行了