如果elif条件问题python2.7

时间:2017-01-17 17:47:16

标签: python python-2.7 if-statement

当我执行以下操作时,条件课程级别6超过260分,数学时为0,我没有得到“不幸的是你不满足要求升级到第三级,至少260分和一个通过数学是必需的。“消息。

但是当条件课程5级以超过260分和数学0分运行时,我确实收到了消息?

if course == 5:
    print"Your total CAO points are " ,total

elif course == 6:
        print"Your total CAO points are " , total*1.25
        total= total*1.25

if total >=260: 
    if math>=25:
        print "You are eligible to progress to third level"

elif total >=260:
     math=0
        print "Unfortunately you do not meet the requirements to progress to third level, At least 260 points and a pass in Mathematics are required."

elif total <=260:
    math=0
    print "Unfortunately you do not meet the requirements to progress to third level, At least 260 points and a pass in Mathematics are required."

1 个答案:

答案 0 :(得分:1)

在if-elif-else套件中进行一次测试后,将不会检查其他任何测试。在您的代码中,elif中的条件与if中的条件相同。这意味着永远无法访问elif下的代码。

if total >= 260: 
    if math >= 25: # failing this if-statement does not negate the "if total >= 260"
        print "You are eligible to progress to third level"

elif total >= 260:  # will never be reached because it's identical to prior if-statement
    math=0
    print "Unfortunately you do not meet the requirements to progress to third level, At least 260 points and a pass in Mathematics are required."

elif total <= 260: # is 260 in our out? if 260 is a pass change from <= to <
    math=0
    print "Unfortunately you do not meet the requirements to progress to third level, At least 260 points and a pass in Mathematics are required."

有一种更好的方式来记录你的条件。您的错误消息包含单词and

  

至少需要260分才能通过数学考试。

因此,在条件中使用and来简化逻辑:

if total >= 260 and math >= 25:     # must meet both conditions
    print "You are eligible to progress to third level"
else:
    math = 0
    print "Unfortunately you do not meet the requirements to progress to third level. "\
        "At least 260 points and a pass in Mathematics are required."