-1

当我遇到这个涉及循环的问题时,我正在尝试学习编程并且正在做一些练习。这是问题:

创建一个程序来获取用户今年的课程分数(询问用户他们上了多少门课)。告诉他们有多少课不及格,最好的成绩和最差的成绩。

我不知道如何显示最好的标记和最差的标记。这是我得到的:

count = 0
total = 0

while True:
    mark = input("Enter a mark (0-100) <-1 to exit> ")
    if mark == -1:
        break
    elif mark < 50:
        count += 1
        total += mark

print "You failed",count,"class(es). "
4

2 回答 2

2

添加另外两个辅助变量:worstmarkbestmark.

然后在您的循环中,推理输入是否低于 currentworstmark或高于bestmark. 相应地分配值。

于 2013-03-31T22:46:36.813 回答
0

希望这会有所帮助:

# list of marks
marks = []

# get marks from user
while True:
    mark = input("Enter a mark (0-100) <-1 to exit> ")
    if mark < 0:
        break
    elif mark <= 100:
        marks.append(mark)

# count number of classes failing 
failing = len([f for f in marks if f<50])
best = max(marks)
worst = min(marks)

# check if a least one mark entered 
if (len(marks) > 0):
    print "The number of classes you are failing:",failing
    print "Your best class score:",best
    print "Your worst class score",worst
else:
    print "Your are not taking any classes!"

演示:

$ python classes.py
Enter a mark (0-100) <-1 to exit> -1
Your are not taking any classes!

$ python classes.py
Enter a mark (0-100) <-1 to exit> 30
Enter a mark (0-100) <-1 to exit> 40
Enter a mark (0-100) <-1 to exit> 50
Enter a mark (0-100) <-1 to exit> 60
Enter a mark (0-100) <-1 to exit> 70
Enter a mark (0-100) <-1 to exit> 80
Enter a mark (0-100) <-1 to exit> -1
The number of classes you are failing: 2
Your best class score: 80
Your worst class score 30
于 2013-03-31T23:15:39.110 回答