Home > Blockchain >  Stuck on this Python program
Stuck on this Python program

Time:01-26

Image to problem

The for loop works, though I can't figure out how to put the grade on a single line as shown in the photo. It asks for grades individualy when ran instead.

Here is my code:

num_students = int(input("Enter the number of students: "))
scores = []
for i in range(num_students):
    scores.append(int(input("Enter a score: ")))
best_score = max(scores)
for i in range(num_students):
    if scores[i] >= best_score - 10:
        grade = "A"
    elif scores[i] >= best_score - 20:
        grade = "B"
    elif scores[i] >= best_score - 30:
        grade = "C"
    elif scores[i] >= best_score - 40:
        grade = "D"
    else:
        grade = "F"
    print("Student", i, "score is", scores[i], "and grade is", grade)

CodePudding user response:

Use a single input() call instead of a loop, and use .split() to get each individual score.

num_students = int(input("Enter the number of students: "))
scores = input(f"Enter {num_students} scores: ")
scores = [int(score) for score in scores.split()]

CodePudding user response:

As John Gordon answered, your main issue is calling input inside a loop. That dictates that each user response will be on its own line. To fix this, call input once, then break the resulting string up using .split(). Split when called with no arguments will break a string into a list at each space.

Here is an example of how to do this (without the f strings and list comprehensions from John's answer):

num_students = int(input("Enter the number of students: "))
score_string = input("Enter "   str(num_students)   " scores: ")

scores = []
for score in score_string.split():
    scores.append(int(score))
  • Related