我正在尝试学习编程,当我遇到涉及循环的这个问题时,我正在做一些练习。这是一个问题:
创建一个程序,该程序获取用户今年为其班级添加的标记(询问用户他们正在参加多少课程)。告诉他们他们失败的班级数量,最佳分数和最差分。
我不知道如何显示最佳标记和最差标记。这是我得到的:
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). "
答案 0 :(得分:2)
再添加两个辅助变量:worstmark
和bestmark
。
然后在你的循环中,推断输入是否低于当前worstmark
或高于bestmark
。相应地分配值。
答案 1 :(得分: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