-1

我正在使用 python 并在大学做家庭作业,因为这个我不能让 if-elif-else 函数工作.. D:

这是我的代码,我无法让它正常工作。它只打印没什么可吹嘘的。即使分数是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

4 回答 4

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!"
于 2013-09-12T04:56:50.853 回答
4

您可以使用and运算符正确地执行逻辑,或者更好地a<b<c使用 Python 中布尔值的语法。逗号通常表示 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!"
于 2013-09-12T04:59:36.310 回答
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!"
于 2013-09-12T05:00:22.430 回答
-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!"
于 2013-09-12T05:19:01.210 回答