I need to have the user input a certain amount of numbers (5) and have them stored in a text file. I also need to find the average of those numbers. Would I use the sum function for that and then divide by 5?
This is for python and I use the IDLE 3.4 version on OS X.
lst = list() #creates a list to later store nubers in
def addtolist(): #creates a function for adding numbers to the list
def listcount(): #
try:
lst.append(int(input("Enter a number:")))
except ValueError:
print("That was not a number")
print(lst)
listcount()
yes = ["yes", "y"]
no = ["no", "n"]
yup = ["yes", "y"]
nah = ["no", "n"]
enteragain = input("Enter another number? yes/no")
if enteragain in yes:
print("Ok")
elif enteragain in no:
print("We'll try again")
addtolist()
runagain = input("Are those the numbers you wanted to enter?")
if runagain in yes:
print("Ok")
elif runagain in no:
print("We'll try again")
addtolist()
addtolist()
I fiddled a little with it and instead of storing the list as a text file I decided to keep it in list form. Here is what I came up with at the end:
lst = list()
def addtolist(): #creates a function for adding numbers to the list
def listcount(): #
try:
lst.append(int(input("Enter a number: ")))
except ValueError:
print("That was not a number")
addtolist()
print(lst)
listcount()
yes = ["yes", "y"]
no = ["no", "n"]
def playagain():
enteragain = input("Enter another number? yes/no?... ")
if enteragain in no:
print("Ok!\n Calculating average.../n")
elif enteragain in yes:
print("Ok then!")
addtolist()
else:
print("Please type either yes or no")
playagain()
playagain()
addtolist()
total = sum(lst)
numbers = len(lst)
average = total/numbers
print("The average of", lst, "is", average)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.