SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:11 | ISBN:978013274719 | Edition: 6

Question

(Find the two highest scores) Write a program that prompts the user to enter the number of students and each student’s score, and displays the highest and secondhighest scores

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Find the two highest scores Program Code:

# Prompt the user to enter the number of students
numOfStudents = int(input("Enter the number of students: "))

# Initialize variables for highest and second highest scores
highestScore = float("-inf")
secondHighestScore = float("-inf")

# Iterate over each student's score
for i in range(numOfStudents):
    score = float(input("Enter the score for student {}: ".format(i + 1)))

    # Check if the current score is higher than the highest score
    if score > highestScore:
        secondHighestScore = highestScore
        highestScore = score
    # Check if the current score is higher than the second highest score but lower than the highest score
    elif score > secondHighestScore and score < highestScore:
        secondHighestScore = score

# Display the highest and second highest scores
print("\nThe highest score is:", highestScore)
print("The second highest score is:", secondHighestScore)

Executed Output:

Enter the number of students: 6
Enter the score for student 1: 200
Enter the score for student 2: 50
Enter the score for student 3: 100
Enter the score for student 4: 80
Enter the score for student 5: 90
Enter the score for student 6: 80

The highest score is: 200.0
The second highest score is: 100.0

 

0 0

Discussions

Post the discussion to improve the above solution.