Write a function ioAve() which repeatedly prompts the user to enter numbers (of
ID: 3553064 • Letter: W
Question
Write a function ioAve() which repeatedly prompts the user to enter numbers (of any sign), followed by any printable non-numerical character (to signal the end of the sequence of numbers). A numerical character is any digit 0, 1, . . . , 9, the decimal dot ., e for scientific notation, and the signs +, ?. (Examples of non-numerical characters are the letters other than e.) As soon a non-numerical character is entered, the function ioAve calls ave(L) (an auxiliary function) and returns the average of the numbers that were entered. Don
Explanation / Answer
Below is a function ioAve that repeatedly prompts the user to enter numbers of any sign followed by any printable non-numerical character and returns the average of the numbers that were entered in less than 10 lines. I tried to add comments so you can understand what's going on in it. Let me know if you need more explanation! :)
def ioAve():
num_inputs = [] # A list of user-inputted numbers
while True:
num = raw_input("Enter a number of any sign or a non-numerical character to average: ")
try:
# float automatically accepts numbers with any digit 0, 1,..., 9, the decimal dot, e for scientific notation, and the signs +, -.
num_inputs.append(float(num))
except ValueError:
break
return ave(num_inputs);
def ave(L):
""" Return the average of a list L of numbers. """
if L == []: return 0
return sum(L)/len(L)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.