3

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!

2
  • 1
    Hints: your function takes no argument just yet, you may want to change that. There is a sum() function that takes a sequence. Commented Oct 4, 2013 at 21:07
  • I want to say thank you for being a first-time poster (posting homework even), but still making a clear post that doesn't simply ask use to write code for you but instead asks for improvement of existing code. As a result you have gotten good responses. Commented Oct 4, 2013 at 21:51

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You should add a parameter to your definition of average which accepts my_list.
wasn't sure if the op had learned about parameters yet - anyway, it is not 100% necessary, the function still works fine @ShashankGupta
1

You can simply use avg = sum(my_list)/len(my_list) if (len(my_list) != 0) else 0 to get your average if you want to use the library functions.

Otherwise, if you just want to know how to change your code, take a look at the error it generates:

Traceback (most recent call last):
  File "file.py", line 12, in <module>
    average(my_list)
TypeError: average() takes no arguments (1 given)

Obviously, we need to pass in the list to average. Here's a very naive way of computing the average

def average(l):
  s =0
  c = 0
  for val in l:
    s += val
    c +=1
  avg = (s/c if (c != 0)  else 0)
  print("the average of your numbers is: " +str(avg)+ ".")

This could be easily replaced by my earlier code:

def avg(l):
  avg = sum(l)/len(l) if (len(l) != 0) else 0
  print("the average of your numbers is: " +str(avg)+ ".")
  # or
  if (len(l) !=0):
    avg = sum(l)/len(l)
  else:
    avg = 0
  print("the average of your numbers is: " +str(avg)+ ".")

Comments

1

The solution I provided makes use of Python 3, which you appear to be using.

    #!/usr/bin/env python3

    """The segment below takes user input for your list."""

    userInput = input("Enter a comma-delimited list of numbers \n")
        userList = userInput.split(",")
        try:
            data_list = [float(number) for number in userList]
        except ValueError:
            print("Please enter a comma-delimited list of numbers.")


    def list_modifier(list_var):
       """Print the original list, average said list, modify it as needed,
          and then print again."""
       print("Your list is: " + list_var)
       average = sum(list_var) / len(list_var)  # Divide list by sum of elements
       for x in list_var:
            x += 1
       print("Your modified list is: " + list_var)

    list_modifier(data_list)

I used a little bit of fancy stuff to take the user input that handles errors if they arise, but really you should not be worrying about stuff like that.

The split() string method just splits up strings into a list of individual smaller strings using whatever parameter you give it. In this case, I split it up on every comma. I added error handling because if you end a string in a comma, the input function will not work.

I also made use of list comprehension, a type of expression in python that creates lists based on the parameters passed within the brackets. This is seen in the code below:

[float(number) for number in userList]

This takes each string within the list of strings created by split() and makes it into a number. We now have our desired list of numbers.

Beyond that, we have the list_modifier function, which first states the list of numbers with string concatenation. It then uses the sum() function to find the sum of all of the elements of the list and divides that sum by the length of the list.

The for code block takes each element in the list and adds one to it. String concatenation is used once again to finally show our modified list.

I really hoped this solution helped, sorry if it was a bit overly-complex. Try/except blocks can be quite useful for handling errors, I really recommend you look into them later on. See the Python documentation as well if you want to get ahead in class.

Good luck and have fun!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.