pythonlistloopsdynamicslice

python beginner : Dynamically modifying a python list with indexing/slicing to preform arithmetic operators


I have been stuck trying to write code that will dynamically take user input from a list and preform general arithmetic operators. In order to work around this I used indexing and slicing which did solve my problem temporarily but a new problem rose from doing this.

listgrades= []

num_students = int(input("How many students are you evaluating?"))

def student_info():
    for i in range(0, num_students):
        student_name=input("Enter your name here: ")
        studnet_age=input("Enter your age here: ")
        student_total_grade=int(float(input("What is your total grade")))
        listgrades.append(student_total_grade)

student_info()
grades_sum= (listgrades[0] + listgrades[1] + listgrades[2]) / num_students
print(f"The average of all the student grades is {grades_sum}")

`

I'm trying to change the (listgrades[0] + listgrades[1] + listgrades[2]) to something more changeable, workable and scalable

I was trying to look and find a solution or a way to work around this but I hit a dead end and I ran out of ideas at this point.

I think a loop of some sorts might work for this but I'm not sure.

side note: I kinda looked into numpy and I can't use it since my school lab computers won't allow anything out of the default python module library.


Solution

  • I have some general advice and some specific suggestions.

    For general advice, to see what built in methods are available is to use python itself.

    At the command line type python3 then, within python type dir(list) and you will see the available methods for lists. You get more detailed information about any specific method by typing help and the class you are interested in followed by a dot, than the method name. For example help(list.count). You can also type help(list) to get a more in depth list of all the functions and instructions for use. Type space to continue to the next screen, and b to backup a screen. Type q to end the help screens. To exit python type exit()

    More specifically, I agree that a loop would be a more dynamic direction to go, given you are asking how many students to evaluate in your input.

    One way to loop through your list would be:

    for x in listgrades:
        sum = sum + x
    

    Of course, you can perform other math operations inside the loop, or in similar loops. Presumably you will initialize your value before the loop.

    At some point you may need to count how many grades are in your list. Fortunately, there's a built-in method for lists that gives you that information called count. You'll see this if you use python's dir(list) or help(list).

    number_of_grades = listgrades.count
    

    I think this will point you in the direction you were thinking with the code, without giving away much in exactly how, which is what you are learning. Best of luck!