Как найти второе наименьшее значение входов, используя циклы while в python? - PullRequest
0 голосов
/ 25 октября 2019

студентов = int (вход ('Введите количество студентов:')) counter = 1

while (counter <= студентов): </p>

name = input('Please enter student ' + str(counter) + ' name:')
score = int(input('Please enter student ' + str(counter) + ' score:'))

lowest = 100
secondlowest = 100

if (score < lowest):
    secondlowest = lowest
    lowest = score

elif score > lowest and score < secondlowest:
    secondlowest = score

counter = counter + 1

print("2nd lowest student is " + name + " with score " + str(secondlowest))

Ответы [ 2 ]

1 голос
/ 25 октября 2019

вам просто нужны две переменные, чтобы отслеживать две наименьшие оценки

  • Если самая новая оценка ниже самой низкой оценки, обновите ее и установите второй наименьший на первый

  • В противном случае, если новейшая оценка ниже текущей второй наименьшей, просто обновите ее новым значением.

0 голосов
/ 26 октября 2019
while True: # Use a "while|true|break to ensure input is correct
    try: 
        students = int(input('Enter number of students: ')) # I fnot an int, raise error
        break # Stops while loop
    except: # Catch not an int error
        print("Input 'students ' must be an integer") # Print explanation, go to next while

counter = 0
lowest_score  = None # None versus high number to avoid limits
lowest_name   = None
second_lowest_score = None
second_lowest_name  = None

testlist = [] # Just for checking alidity of order. Delete before submission

while (counter < students):
    while True: # Get new input
        try: 
            score = int(input('Please enter student {} score:'.format(counter)))
            break
        except: 
            print("Score must be an integer...")

    name = input('Please enter student  name:'.format(counter))

    testlist.append(score) # Just for checking, Delete       

    # Handle first loop
    if lowest_score is None: 
        lowest_score = score
        lowest_name = name
        continue

    # Handle first loop
    if second_lowest_score is None:
        if score > lowest_score:
            second_lowest_score = score
            second_lowest_name = name
        else:
            second_lowest_score = lowest_score
            second_lowest_name = lowest_name
            lowest_score = score
            lowest_name = name
        continue # next iteration of main while

    if (score < second_lowest_score) :
        if (score >= lowest_score) :
            second_lowest_score = score
            second_lowest_name = name
        else:
            second_lowest_score = lowest_score
            second_lowest_name = lowest_name

    if score < lowest_score:
        lowest_score  = score
        lowest_name = name

    counter = counter + 1

print('2nd lowest student is ',
      name, 
      'with score', 
      second_lowest_score)
print(sorted(testlist))
...