Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User input average

Tags:

python

My teacher doesn't teach us in class and I am trying to learn this on my own. This is what I am supposed to do and this is how far I have gotten. Any help would be greatly appreciated!

  • Takes a list of five numbers from the user
  • Prints the list
  • Prints the average
  • Modifies the list so each element is one greater than it was before
  • Prints the modified list
 def average():
     x=a+b+c+d+e
     x=x/5
     print("the average of your numbers is: " +x+ ".")

 my_list =[ ]
 for i in range (5):
     userInput = int(input("Enter a number: ")
     my_list.append(userInput)
     print(my_list)
 average(my_list)

Thanks for your help you tube can only go so far!

like image 357
user2848112 Avatar asked Feb 01 '26 21:02

user2848112


1 Answers

The main functions that are going to be useful to you here are sum() and len()

sum() returns the the sum of items in a iterable

len() returns the length of a python object

Using these functions, your case is easy to apply these too:

my_list = []
plus_one = []

for x in range(5):
    my_list.append(x)
    plus_one.append(x+1) 

print my_list
print plus_one

def average():
    average = sum(my_list) / len(my_list) 
    return average

print average()

As Shashank pointed out, the recommended way is to define a parameter in the function and then pass the argument of your list when calling the function. Wasn't sure if you had learned about parameters yet, so I originally left it out. Here it is anyway:

def average(x):
    # find average of x which is defined when the function is called

print average(my_list) # call function with argument (my_list)

The benefit of this is if you have multiple lists, you don't need a new function, just change the argument in the function call.

like image 168
samrap Avatar answered Feb 04 '26 11:02

samrap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!