在python中评分程序,卡在if else语句上

时间:2014-03-24 18:28:48

标签: python loops if-statement nested-loops

我仍然是python的新手,我必须编写这个程序,用户输入作业成绩,类型'完成'并获得他们的成绩。我差不多完成了它,但是当它进入循环时我一直收到错误信息:

TypeError:unorderable类型:str()> INT()。

print("Enter the homework scores one at a time. Type 'done' when done")
hwCount = 1
totalScore = 0
strScore = input("Enter the HW#" + str(hwCount) + " score: ")
while strScore != "done":
    if ( strScore is int and strScore >= 0 and strScore <= 10 ):
        totalScore = totalScore + strScore
        hwCount = hwCount + 1
    elif ( strScore is int and strScore < 0 or strScore > 10):
    print("Please enter a number between 0 and 10")
    else:
        print("Please enter only whole numbers")
    strScore = input("Enter HW#" + str(hwCount) + " score: ")

我试过了:

strScore = int(input("Enter the HW#" + str(hwCount) + " score: ")

但它只打印else语句,然后我得到了和以前一样的错误。如果有人可以帮我解决这个问题,我真的很感激

3 个答案:

答案 0 :(得分:2)

strScore是一个字符串。您的while循环应如下所示:

while strScore != "done":
    try:
        score = int(strScore)
        if score >= 0 and score <= 10:
            totalScore = totalScore + score
            hwCount = hwCount + 1
        else:
            print("Please enter a number between 0 and 10")
    except ValueError:
        print("Please enter only whole numbers or 'done'")
    strScore = input("Enter HW#" + str(hwCount) + " score: ")

当您在代码中显示时,有三种情况需要处理 - 用户输入有效分数,用户输入有效数字但分数无效,用户输入无效数字。如果用户输入了无效的整数,尝试int(strScore)会引发ValueError,我们可以抓住并报告。知道否则score将是有效int,我们只需要检查它是否是有效分数,允许您将elif更改为简单的else

答案 1 :(得分:0)

strScore = int(input("Enter the HW#" + str(hwCount) + " score: ")

无效,因为你有

while strScore != 'done':

需要strScore成为字符串(最终)。请参阅Rob Watts对代码的回答(打败我)

答案 2 :(得分:0)

input(python3)总是返回一个str。您需要将其转换为整数比较和添加。我喜欢从我的其他工作中打破我的有效输入逻辑,所以如果你定义这样的函数(希望可重用):

def get_valid_input(prompt, min_score=0, max_score=10):
   while True:
        text = input(prompt).strip()
        if text == 'done':
            return text
        try:
            score = int(text)
        except ValueError:
            print("Please enter a number or done")
            continue
        if min_score <= score <= max_score:
            return score
        else:
            print("Please enter a number between %s and %s" % (min_score, max_score))

然后获得你的硬件分数,这是一件简单的事情

total_score = 0
hw_count = 1
score = get_valid_input("Enter HW#%s score: " % hw_count)
while score != "done":
    total_score += score
    hw_count += 1
    score = get_valid_input("Enter HW#%s score: " % hw_count)