2

I have to use the append method to get info from the user however I am only suppose to take 10 lines from the user and not suppose to ask them if they have another set of information to enter. Can anyone tell me how to stop a list_append without asking the user to stop it?

The following is my code in python.

    #set limit
    num_grades = 10

    def main():
       #making of the list
       grades = [0] * num_grades

       #hold the index
       index = 0

       #ask the user for the info
       print('Please enter the final grades for 10 students: ')

       #put the info into the list with a loop 
      while index < num_grades:
        grade = input('Enter a grade: ')
        grades.append(grade)
   main()

4 Answers4

1

Your given code is missing only one thing: you forgot to increment the index each time through the loop.

Do this better with a for loop:

for index in range(num_grades):
  grade = input('Enter a grade: ')
  grades.append(grade)
Prune
  • 76,765
  • 14
  • 60
  • 81
0

Your issue is that you are forgetting to increment index inside the while loop you have created, and hence it is always zero.

Just adding a index += 1 line inside the loop will fix your issue.

As stated by @Prune, a for loop would be much more suitable in this situation.

Ziyad Edher
  • 2,150
  • 18
  • 31
0

This kind of thing is easily handled by for loops. Here is your code edited:

num_grades = 10

def main():
   #making of the list
   grades = []

   #ask the user for the info
   print('Please enter the final grades for 10 students: ')

   #put the info into the list with a loop 
   for i in range(num_grades):
      grade = input('Enter a grade: ')
      grades.append(grade)
main()
0

As @Wintro has mentioned, the issue was that you forgot to increment the index inside the while loop. So the working solution looks as follows:

num_grades = 10

def main():
    #making of the list
    grades = [0] * num_grades

    #hold the index
    index = 0

    #ask the user for the info
    print('Please enter the final grades for 10 students: ')

    #put the info into the list with a loop 
    while index < num_grades:
        grade = input('Enter a grade: ')
        grades.append(grade)
        index += 1

main()
Alex Kiura
  • 34
  • 4
  • Thank you I am having trouble getting the avg, high grade, and low grade. my program will not work with following code it takes the highest and lowest of every information entered by the user num_grades = 10 intcount = 0 def main(): grades = [] print('Please enter the final grades for 10 students: ') #put the info into the list with a loop for i in range(num_grades): grade = input('Enter a grade: ') grades.append(grade) print('Maximum Grade: ', max(grades)) print('Minimum Grade: ', min(grades)) –  Apr 06 '17 at 18:16
  • (1) This is a separate problem; please post as a separate question. (2) Don't post code in comments; edit it into the question (or answer when you get there). – Prune Apr 06 '17 at 22:41