Python if-elif-else在理论上不应该工作?

时间:2013-09-12 04:54:38

标签: python

我正在使用python和大学的家庭作业,现在已经晚了因为这个我无法让if-elif-else功能起作用.D:

这是我的代码,我无法让它正常工作。它只打印Nothing来吹嘘。即使得分是1000。

score = raw_input("What is your score?")

if (score >= 0, score <= 999):
    print "Nothing to brag about."

elif (score >= 1000, score <= 9999):
    print "Good Score."

elif (score >= 10000):
    print "Very Impressive!"

else:
    print "That's not a legal score!"

4 个答案:

答案 0 :(得分:8)

首先,您不需要这些括号;

其次,您需要使用and代替,;

第三,您需要将输入投放到int,因为raw_input函数会返回string

如果在交互式终端中键入help(raw_input),您应该看到定义:

raw_input(...)
    raw_input([prompt]) -> string

固定代码:

score = int(raw_input("What is your score?"))

if score >= 0 and score <= 999:
    print "Nothing to brag about."

elif score >= 1000 and score <= 9999:
    print "Good Score."

elif score >= 10000:
    print "Very Impressive!"

else:
    print "That's not a legal score!"

答案 1 :(得分:4)

您可以使用and运算符正确地执行逻辑,或者甚至更好地使用Python中a<b<c布尔值的语法。逗号通常表示Python中的元组。另外,请不要忘记将输入转换为int

score = int(raw_input("What is your score?"))

if 0 <= score <= 999:
    print "Nothing to brag about."

elif 1000 <=score <= 9999:
    print "Good Score."

elif score >= 10000:
    print "Very Impressive!"

else:
    print "That's not a legal score!"

答案 2 :(得分:2)

首先,您需要将raw_input()的结果转换为整数。

其次,Python不使用围绕比较器的括号。您拥有的结构是布尔值的元组,这将导致意外的结果。

最后,Python可以将比较器链接在一起,以生成更易读的代码。

score = raw_input("What is your score?")

try:
    score = int(score)
except:
    # Casting a non-number to an integer will throw an expection.
    # You need to handle that in some way that makes sense.
    score = -1 # Setting the score to -1 will at least cause the else branch to fire.

if 0 <= score <= 999:
    print "Nothing to brag about."
elif 1000 <= score <= 9999:
    print "Good Score."
elif score >= 10000:
    print "Very Impressive!"
else:
    print "That's not a legal score!"

答案 3 :(得分:-1)

试试这个:

score = raw_input("What is your score?")

if ( int(score) <= 999 and int(score) >= 0):
    print "Nothing to brag about."

elif (int(score) >= 1000 and  int(score) <= 9999):
    print "Good Score."

elif (int(score) >= 10000):
    print "Very Impressive!"

else:
    print "That's not a legal score!"