【问题标题】:Finding the 2nd lowest number without using lists, functions, or dictionary在不使用列表、函数或字典的情况下查找第二小的数字
【发布时间】:2020-03-08 14:50:14
【问题描述】:

我正在尝试创建一个程序,其中用户输入一定数量的学生、他们的姓名和他们的考试成绩,该程序应该打印第二低的分数和学生姓名。我是 python 新手,还没有学习过列表和字典之类的集合,所以请使用 if、else 和 while 循环保持简单。下面是我到目前为止打印第二高而不是第二低的代码。

n= int(input("Enter number of students:"))
low_name= ','
low_name_2= ','
low_score= 0
low_score_2= 0
for i in range(n):
    name= input("Please enter student" + str(i+1) + "name:\n")
    score= int(input("Please enter student" + str(i+1) + "score:\n"))
    while score < 0 or score > 100:
            print("Please enter score in range of 0-100")
            score= int(input("Please enter student" + str(i+1) + "score:\n"))

    if score > low_score:
           low_name_2 = low_name
           low_score_2 = low_score
           low_name = name
           low_score = score


    elif score > low_score_2:
            low_score_2 = score
            low_name_2 = name
print("2nd lowest student is ", low_name_2 , " with score ", str(low_score_2))

【问题讨论】:

  • 是什么阻止您修改程序以找到第二个最低数?
  • 任务没有说明堆,所以使用堆。

标签: python loops conditional-statements


【解决方案1】:

你的逻辑很接近。只需在声明中将low_scorelow_score_2 更改为101,然后在if 语句中将&gt; 符号更改为&lt; 符号。

最终代码:

n= int(input("Enter number of students:"))
low_name= ','
low_name_2= ','
low_score=101
low_score_2=101
for i in range(n):
    name= input("Please enter student" + str(i+1) + "name:\n")
    score= int(input("Please enter student" + str(i+1) + "score:\n"))
    while score < 0 or score > 100:
        print("Please enter score in range of 0-100")
        score= int(input("Please enter student" + str(i+1) + "score:\n"))

    if score < low_score:
       low_name_2 = low_name
       low_score_2 = low_score
       low_name = name
       low_score = score
    elif score < low_score_2:
       low_score_2 = score
       low_name_2 = name
print("2nd lowest student is ", low_name_2 , " with score ", str(low_score_2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 2019-05-02
    • 1970-01-01
    • 2015-01-02
    • 2020-02-05
    相关资源
    最近更新 更多