I have a program that takes input and adds it to a list and spits out the average of said list. I want to make it so you can type MENU and it will stop the programy() and let you either exit or restart the programy(). Everything works fine until you type MENU (all caps). Thank you everyone! :) Still new to python.
from functools import reduce
def programy():
running = True
print("I output the average of a list that you add files to.")
listy = []
while running == True:
def listaverage(givenlist):
print(sum(listy) / len(listy))
currentnum = input("Please type a number to add to the list: ")
try:
val = int(currentnum)
except ValueError:
if str(currentnum) == "MENU":
running = False
else:
print("Not a number!")
continue
listy.append(int(currentnum))
listaverage(listy)
answer = input("Please type either: EXIT or RESTART")
if str(answer) == "RESTART":
running = True
if answer == "EXIT":
exit
programy()
Traceback (most recent call last):
File "C:\Users\hullb\OneDrive\Desktop\average_via_input.py", line 34, in <module>
programy()
File "C:\Users\hullb\OneDrive\Desktop\average_via_input.py", line 24, in programy
listy.append(int(currentnum))
ValueError: invalid literal for int() with base 10: 'MENU
if str(currentnum) == "MENU":
running = False
sets the while
condition to false
and stops the next iteration from running, but the current one hasn't ended yet, so in int(currentnum)
you are trying to convert "MENU"
to int.
Use isdigit()
instead to check the value
if currentnum.isdigit():
listy.append(int(currentnum))
listaverage(listy)
else:
if str(currentnum) == "MENU":
running = False
else:
print("Not a number!")