Home > database >  Need to use one 'while loop Is it possible to fix this?
Need to use one 'while loop Is it possible to fix this?

Time:09-25

need help to combined one while loop. Need to use one 'while loop Is it possible to fix this code?

     def get_grades(number_of_grades):
        grades = []
        while len(grades) < number_of_grades:
            current_grade = int(input("Please enter a student grade: "))
            grades  = [current_grade]
        return grades
    
    
    def get_highest_grade(grades):
        highest_grade = grades[0]
        current_grade_index = 1
        while current_grade_index < len(grades):
            if grades[current_grade_index] > highest_grade:
                highest_grade = grades[current_grade_index]
            current_grade_index = current_grade_index   1
        return highest_grade
    
    
    number_of_grades = int(input("How many students are there?: "))
    grades = get_grades(number_of_grades)
    highest_grade = get_highest_grade(grades)
    print(f"The highest grade is {highest_grade}") 

CodePudding user response:

Your question is unclear, you should add more content next time.

What do you mean by "fix this code"? It looks like it works as intended. Also try to use for loops instead of while loops to avoid infinite loops. If your goal is to have only one loop to input the grades and get the highest one, here's a solution :

def get_highest_grade(number_of_grades) :
    highest_grade = 0
    for i in range(number_of_grades) :
        current_grade = int(input("Please enter a student grade: "))
        if current_grade > highest_grade :
            highest_grade = current_grade
    return highest_grade

CodePudding user response:

not sure what you mean that you want one while loop but you can eliminate the while loop in the second fucntion 'get_highest_grade'.

You can just use python's max() function.

def get_highest_grade(grades):
    highest_grade = max(grades)

    return highest_grade
  • Related