"""read file and store into database"""
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
artist=[""]
song=[""]
album=[""]
genre=[""]
index=0
for line in f:
if index==0:
artist.append(line)
index=index+1
elif index==1:
song.append(line)
index=index+1
elif index==2:
album.append(line)
index=index+1
elif index==3:
genre.append(line)
index=index+1
elif index==4:
index=0
while 1:
selection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Search\n2.Recommend\n3.Edit\n4.Save\n"))
if selection == 1:
print "You selected Search"
searchselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Display All Songs\n2.Display All Artists\n3.Search By Artist\n4.Display All Genres\n5.Search by Genre\n6.Display All Playlists\n7.Search By Playlist\n"))
if searchselection == 1:
print '[%s]' % ''.join(map(str, song))
elif searchselection == 2:
print '[%s]' % ''.join(map(str, artist))
elif searchselection == 3:
artistsearch = str(raw_input("\nWhat artist are you searching for?\n"))
artist.index(artistsearch)
print value
elif searchselection == 4:
print '[%s]' % ''.join(map(str, genre))
elif searchselection == 5:
print "display"
elif searchselection == 6:
print "display"
elif searchselection == 7:
print "display"
break
elif selection == 2:
print "You selected recommend."
recommendselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Recommend by Song Title\n2.Recommend by Artist Name\n"))
if recommendselection == 1:
songrec = str(raw_input("Please enter the song title\n"))
elif recommendselection == 2:
artistrec = str(raw_input("Please enter the Artist's name\n"))
break
elif selection == 3:
print "You selected edit."
editselection = int(raw_input("Please select the number that corresponds with what you would like to do.\n1.Add a New Song\n2.Create New Playlist\n3.Add a song to a current playlist"))
if editselection == 1:
songadd = str(raw_input("Please enter the EVERYTHING\n"))
elif editselection == 2:
playistcreate = str(raw_input("Please enter the name of the Playlist\n"))
elif editselection == 3:
playlistadd = str(raw_input("Please enter the name of the playlist\n"))
break
elif selection == 4:
print "You selected Save."
f.close()
break
So that is what I have thus far. This is an ongoing python project, and right now I am stumped; I am trying to search by artist like if Justin Timberlake is typed in by the user as "artistsearch" then I want the index to be pulled so that I can match the index in the song list and display that information to the user.
Any help determining why Justin Timberlake is not a value on the list even though the name shows up when I run the display all artists option would be greatly appreciated.
Also being pointed in the right direction for matching list indexes would be great as well. This is an example of the tunes.txt:
Alicia Keys
No One
As I Am
R&B/Soul;Syl tunes
Everything But the Girl
Missing
Amplified Heart
Alternative;Syl tunes
Gathering Field
Lost In America
Lost In America
Rock
Ellie Goulding
Burn
Halcyon
Pop;Road tunes
Justin Timberlake
Mirrors
Mirrors (Radio Edit) - Single
Pop;Syl tunes
I think you should create a specific class for the data you want to store, and then create a list of objects that instantiate such class:
class Song():
"""Class to store the attributes for each song"""
def __init__ (self):
self.artist = ""
self.song = ""
self.album = ""
self.genre = ""
# List to store all the Song objects
songs_list = []
f = open('C:\\Users\\user.name\\Desktop\\tunes.txt','r')
index=0
for line in f:
# Instantiate an empty Song object
s = Song()
if index == 0:
s.artist = line
index=index+1
elif index == 1:
s.song = line
index = index + 1
elif index == 2:
s.album = line
index = index + 1
elif index == 3:
s.genre = line
index = index+1
elif index == 4:
index = 0
songs_list.append(s)
Related
I have a program that is for conversions of simple metrics. I'm a super noob to python and could use a little help.
def main():
use_menu()
if feet_inches():
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
feet_inches()
elif selection == 2:
yards_feet()
elif selection == 3:
miles_yards()
elif selection == 4:
miles_feet()
def get_menu():
print('1. Convert feet to inches')
print('2. Convert yards to feet')
print('3. Convert miles to yards')
print('4. Convert miles to feet')
print('5. Exit')
def feet_inches():
feet2inches = int(input('Enter the number of feet:'))
answer1 = feet2inches / 3
return answer1
def yards_feet():
yards2feet = int(input('Enter the number of yards:'))
answer2 = yards2feet * 3
return answer2
def miles_yards():
miles2yards = int(input('Enter the number of miles:'))
answer3 = miles2yards * 1760
return answer3
def miles_feet():
miles2feet = int(input('Enter the number of miles:'))
answer4 = miles2feet * 5280
return answer4
main()
How do I print the returned values in my main function? I keep getting unresolved reference when I try to set answer1 to a variable in the main function. I'm also struggling with how to write the if/elif for that. Just a little nudge in the right direction would be appreciated.
Line 3:
if feet_inches():
there is no conditional action underneath.
You could try something like this: Remove line 3 above.
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
fi = feet_inches()
print(fi)
elif selection == 2:
yf = yards_feet()
print(yf)
elif selection == 3:
my = miles_yards()
print(my)
elif selection == 4:
mf = miles_feet()
print(mf)
You can use return statements in the use_menu aswell. And then set the answer equal to what is returned by that function in the main function.
def main():
answer = use_menu()
print(answer)
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
return feet_inches()
elif selection == 2:
return yards_feet()
elif selection == 3:
return miles_yards()
elif selection == 4:
return miles_feet()
You could change your code as follows:
def main():
# First, retrieve function to be applied
func = use_menu()
if func is not None:
# Apply function - Could be done in one liner
res = func()
print(res)
def use_menu():
get_menu()
selection = int(input('Please make a menu selection:'))
if selection == 1:
return feet_inches
elif selection == 2:
return yards_feet
elif selection == 3:
return miles_yards
elif selection == 4:
return miles_feet
else:
return None
First time posting so apologizes if formatting is incorrect. My program has 2 lists for now. I I will be adding 4 more after solving this initial issue. One for and item the user selects, and a second with prices for the each item. I have written a code for user selection which runs.
My issue comes with the code for the program associating the item selected with the price list. My first if statement registers item_price as a float, which I gives me what I need. Item_price in the following elif statements are being seen as a list. How can I change them to a float so that the price prints instead of the list?
food=["burger", "pizza", "hotdogs", "tacos"]
food_price=[8.99, 22.50, 3.50, 6.00]
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
#if user selects [n]
else:
return (None)
#item price function
def get_item_price(item_price,item,item_list):
if item == item_list[0]:
item_price = item_price[0]
elif item == item_list[1]:
item_price == item_price[1]
elif item == item_list[2]:
item_price == item_price[2]
elif item == item_list[3]:
item_price == item_price[3]
return item_price
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
entree_price = get_item_price(food_price,entree_choice,food)
print(entree_price)
I answered this for myself shortly after. I was using == instead of = for all of my elif statements. I feel dumb but writing this out helped me solve it.
You could simplify things further by using a dictionary to store your data :
food_price = {"burger":8.99, "pizza":22.50, "hotdogs":3.50, "tacos":6.00}
def get_menu_item(item,item_list,):
phrase = "Would you like" + item + "? [y/n] "
response = input(phrase)
if response == "y":
print("Here are your menu options:", item_list)
idx = input("please enter the item you would like from our menu[1,2,3,4]: ")
idx = int(idx) -1
return item_list[idx]
else:
return (None)
entree_choice = get_menu_item(" dinner",food)
print('You have selected: ' + entree_choice + ".")
# if entree_choice is not found in the food_price dictionary, the output becomes the string "Entree choice not available."
entree_price = food_price.get(entree_choice, "Entree choice not available.")
print(entree_price)
I'm trying to use menus to accepts menu options that append an empty list that acts as a cart. When the list is done with i have the option to add more lists if necessary. In the end im supposed to calculate the total number of carts, total number of items, and the total price. The first issue is the calcuation of carts is wrong as it treats every new entry as list rather than na item, which elads to the item count being wrong as well for each cart. Along with this, i get "TypeError: unsupported operand type(s) for +: 'int' and 'str'" when trying calculating the final price and im just not sure what to do
def main():
#Flag for full checking out or not
checkout = False
#Flag to start a new cart or not
new_cart = True
#Placeholder list
cart = []
#List of items
book_list = [['My Own Words', 18.00], ['Grant', 24.50], ['The Overstory', 18.95], ['Becoming', 18.99]]
elec_list = [['HP Laptop', 429.50], ['Eyephone', 790.00], ['Bose Speakers', 220.00]]
cloth_list = [['T-shirt', 9.50], ['Shoes', 45.00], ['Pants', 24.00], ['Nationals Hat', 32.00]]
groc_list = [['Coho Salmon', 12.50], ['Spaghetti', 2.75], ['Milk', 3.99], ['Eggs', 1.99], ['Flat Tire Ale', 9.95]]
while checkout == False or new_cart == True:
#Main Menu
if checkout == False:
#Main Item menu
print("""
1 - Books
2 - Electronics
3 - Clothes
4 - Groceries
c - Continue to checkout
""")
choice = input("Select one of the categories or checkout(1-4 or 'c'): ")
#Variable to return user to past menu
Return = False
if choice == '1':
while Return == False:
#Sub item menu
print("""
1 - "My Own Words", $18.00
2 - "Grant", $24.50
3 - "The Overstory", $18.95
4 - "Becoming", $18.99
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item =='3' or item == '4':
#Adds item onto the the cart
cart.append(book_list[int(item)-1])
elif item == 'x':
#Returns user to main menu
Return = True
else: print("Invalid input try again")
elif choice == '2':
while Return == False:
#Sub item menu
print("""
1 - HP Laptop, $429.50
2 - EyePhone 10, $790.00
3 - Bose 20 Speakers, $220.00
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3':
#Adds item onto the the cart
cart.append(elec_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == '3':
while Return == False:
#Sub item menu
print("""
1 - T-shirt, $9.50
2 - Shoes, $45.00
3 - Pants, $24.00
4 - Nationals Hat, $32.00
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3':
#Adds item onto the the cart
cart.append(cloth_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == '4':
while Return == False:
#Sub item menu
print("""
1 – Coho Salmon, $12.50
2 − Spaghetti, $2.75
3 – Milk, $3.99
4 – Eggs, $1.99
5 – Flat Tire Ale, $9.95
x - return to menu
""")
item = input("Please select from the menu or go back to the categories: ")
if item == '1' or item == '2' or item == '3' or item == '4' or item == '5':
#Adds item onto the the cart
cart.append(groc_list[int(item)-1])
elif item == 'x':
Return = True
else:
print("Invalid input try again")
elif choice == 'c':
checkout = True
print(cart)
else: print("Invalid input, please try again!")
else:
print("Do you want a new cart y/n")
choice = input()
if choice == 'y':
checkout = False
#Create new cart
cart.append([])
elif choice == 'n':
#Proceed to item summary
new_cart = False
else:
print("Invalid Option, Choose again")
#Print total number of carts
print("Total number of carts :",len(cart))
for v in range(len(cart)):
#Increment for each existing cart
print("Cart",v+1)
#Add total number of items within every cart
print("Total Number of items:",len(cart[v]))
#Add total price of items within every cart
print("Total cost of the items: $",sum(cart[v]))
main()
Your cart contains a list of items which themselves are array:
example, i ran your code and your cart looks like this:
[['My Own Words', 18.0], ['My Own Words', 18.0], ['My Own Words', 18.0], ['My Own Words', 18.0]]
you're trying to apply a sum on a position of an array, so for example when you do
sum(cart[0]) you call sum on ['My Own Words', 18.0] so your code tries to do:
'My Own Words'+18 which gives a type error.
if all you need is the just the total price you could just append the prices instead of the whole items, or you could simply append the prices to a seperate array and call sum on that
I was searching on the internet for projects do with python and came up with a Tic Tac Toe game. But now i'm kind of stuck in some part of the code because i can't store the player moves.
Well, to be honest, i maybe know how to do it, but i'll be using A LOT of if, elif and else. Is there another way i can do it without writing 100+ lines of code just to store some data using my current code?
Ps: It needs to be OOP, as i am learning it right now :l
import msvcrt as m # Using it for 'Press any key to continue' thing.
import os
import keyboard
class TicTacToe:
def __init__(self):
self.difficultAI = 1
self.playWith = 1 # 3 = Strings and Numbers
self.playerOne = None
self.PlayerTwo = None
def menuSelection(self):
os.system('cls')
print(f'[1] - Play\n'
f'[2] - Options\n'
f'[3] - Exit')
try:
option = int(input('I\'ll go with '))
except ValueError as valueError:
print(f'Invalid Option\n'
f'Following error: {valueError}\n'
f'Press any key to continue...')
m.getch() # Waiting for any key to be pressed.min
os.system('cls')
objectRun.menuSelection() # Call menuSelection again.
if option == 1:
objectRun.play()
elif option == 2:
pass
elif option == 3:
exit()
else:
print(f'You should choose something between 1 and 3, and not {option}'
f'Press any key to continue...')
m.getch()
objectRun.menuSelection()
def drawBoard(self, topL='?', topM='!', topR='?',
midL='!', midM='?', midR='!',
lowL='?', lowM='!', lowR='?'):
board = {
'top-L': topL,
'top-M': topM,
'top-R': topR,
'mid-L': midL,
'mid-M': midM,
'mid-R': midR,
'low-L': lowL,
'low-M': lowM,
'low-R': lowR,
}
print(' {0} | {1} | {2}\n'
'----------\n'
' {3} | {4} | {5}\n'
'----------\n'
' {6} | {7} | {8}\n'.format(board['top-L'], board['top-M'], board['top-R'],
board['mid-L'], board['mid-M'], board['mid-R'],
board['low-L'], board['low-M'], board['low-R']))
# change that stupid name when done
def play(self):
os.system('cls')
print(f'[1] - Player VS Player\n'
f'[2] - Player VS Machine\n'
f'[3] - Return')
try:
option = int(input('I\'ll go with '))
except ValueError as valueError:
print(f'Invalid Option\n'
f'Following error: {valueError}\n'
f'Press any key to continue...')
m.getch()
objectRun.play()
try:
os.system('cls')
self.drawBoard()
if option == 1:
if self.playWith == 1: # Numbers
isBoardFull = False # Not using it right now, but ok... I guess.
while isBoardFull != True:
print('Player 1, it\'s your turn\n'
'You can choose between 1 (TOP LEFT) up to 9 (BOTTOM RIGHT)')
self.playerOne = int(input('I\'ll go with '))
self.playerOptions()
elif self.playWith == 2: # Strings
pass
else: # Strings and Numbers
pass
elif option == 2:
pass
elif option == 3:
objectRun.menuSelection()
else:
print(f'You should choose something between 1 and 3, and not {option}'
f'Press any key to continue...')
m.getch()
objectRun.play()
except:
print('ERROR AT LINE 126, GO FIND WHAT IS WRONG')
def playerOptions(self):
if self.playerOne == 1:
os.system('cls')
self.drawBoard(topL='X')
elif self.playerOne == 2:
os.system('cls')
self.drawBoard(topM='X')
elif self.playerOne == 3:
os.system('cls')
self.drawBoard(topR='X')
elif self.playerOne == 4:
os.system('cls')
self.drawBoard(midL='X')
elif self.playerOne == 5:
os.system('cls')
self.drawBoard(midM='X')
elif self.playerOne == 6:
os.system('cls')
self.drawBoard(midR='X')
elif self.playerOne == 7:
os.system('cls')
self.drawBoard(lowL='X')
elif self.playerOne == 8:
os.system('cls')
drawBoard(lowM='X')
elif self.playerOne == 9:
os.system('cls')
self.drawBoard(lowR='X')
else:
pass
def options(self):
os.system('cls')
print(f'[1] - Difficult\n'
f'[2] - P\n'
f'[3] - Exit')
try:
option = int(input('I\'ll go with '))
except ValueError as valueError:
print(f'You should choose something between 1 and 3, and not {option}'
f'Press any key to continue...')
m.getch()
objectRun.menuSelection()
self.difficultAI = int(input('[1] - EASY\n'
'[2] - MEDIUM\n'
'[3] - HARD\n'
'I\'ll go with '))
self.playWith = int(input('[1] - NUMBERS\n'
'[2] - STRING\n'
'[3] - BOTH\n'
'I\'ll go with '))
if __name__ == '__main__':
objectRun = TicTacToe()
objectRun.menuSelection()
Store the current board as dictionary within self.
Initialize your board with the default starting characters.
def __init__(self):
self.difficultAI = 1
self.playWith = 1 # 3 = Strings and Numbers
self.playerOne = None
self.PlayerTwo = None
self.board = {'topL':'?', 'topM':'!', 'topR':'?',} #fill in the rest
Your drawBoard would need adjusted like this...
def drawBoard(self):
board = {
'top-L': self.board['topL'],
'top-M': self.board['topM'],
'top-R': self.board['topR'],
And then I would have a separate method for a "move"
def makeMove(self, player, position):
if self.board[position] not in ['X', 'O']:
self.board[position] = player
self.drawboard()
else:
# error statement and send back to make a new move...
In general, I would have separate methods for the main loop of the game vs everything else. Right now you have a lot of things going on inside the main loop when it should be just sending you to different methods of your game like playerOptions, makeMove, drawBoard, etc. until someone wins or ties.
I'm attempting to create a menu-driven program where python will accept a collection of non-negative integers. It will calculate the mean and median and display the values on the screen. I want my first option to be "Add a number to the list/array", I want my second option to be "Display the mean", the third to be "Display the median", the fourth "Print the list/array to the screen", the fifth "Print the list/array in reverse order" and the last option "Quit". So far I have gotten:
def main():
myList = [ ]
addOne(myList)
choice = displayMenu()
while choice != '6':
if choice == '1':
addOne(myList)
elif choice == '2':
mean(myList)
elif choice == '3':
median(myList)
elif choice == '4':
print(myList)
elif choice == '5':
print(myList)
choice = displayMenu()
print ("\nThanks for playing!\n\n")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' \
and myChoice != '4' and myChoice != '5':
print("""\n\nPlease choose
1. Add a number to the list/array
2. Display the mean
3. Display the median
4. Print the list/array to the screen
5. Print the list/array in reverse order
6. Quit
""")
myChoice = input("Enter option---> ")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4' and myChoice != '5':
print("Invalid option. Please select again.")
return myChoice
#This should make sure that the user puts in a correct input
def getNum():
num = -1
while num < 0:
num = int(input("\n\nEnter a non-negative integer: "))
if num < 0:
print("Invalid value. Please re-enter.")
return num
#This is to take care of number one on the list: Add number
def addOne(myList):
while True:
try:
num = (int(input("Give me a number:")))
num = int(num)
if num < 0:
raise exception
print("Thank you!")
break
except:
print("Invalid. Try again...")
myList.append(num)
#This should take care of the second on the list: Mean
def mean(myList):
myList = [ ]
listSum = sum(myList)
listLength = len(myList)
listMean = listSum / listLength
print("The mean is", listMean)
#This will take care of number three on the list: Median
def median(myList):
median = 0
sortedlist = sorted(myList)
lengthofthelist = len(sortedlist)
centerofthelist = lengthofthelist / 2
if len(sortedlist) % 2 ==0:
return sum(num[center - 1:center + 1]) / 2.0
else:
return num[center]
print("The mean is", centerofthelist)
#This will take care of the fourth thing on the list: Print the list (In order)
def sort(myList):
theList.sort(mylist)
print(myList)
#This will take care of the fifth thing on the list
def reversesort(myList):
theList.sort(reverse=True)
print(myList)
main()
After I run the program I can't get past creating the list.
Corrected code with minimum changes:
def main():
myList = []
choice = 1
while choice != 6:
if choice == 1:
option1(myList)
elif choice == 2:
option2(myList)
elif choice == 3:
option3(myList)
elif choice == 4:
option4(myList)
elif choice == 5:
option5(myList)
choice = displayMenu()
print ("\nThanks for playing!\n\n")
def displayMenu():
myChoice = 0
while myChoice not in [1, 2, 3, 4, 5]:
print("""\n\nPlease choose
1. Add a number to the list/array
2. Display the mean
3. Display the median
4. Print the list/array
5. Print the list/array in reverse order
6. Quit
""")
myChoice = int(input("Enter option---> "))
if myChoice not in [1, 2, 3, 4, 5]:
print("Invalid option. Please select again.")
return myChoice
# Option 1: Add a number to the list/array
def option1(myList):
num = -1
while num < 0:
num = int(input("\n\nEnter a non-negative integer: "))
if num < 0:
print("Invalid value. Please re-enter.")
myList.append(num)
# Option 2: Display the mean
def option2(myList):
print("The mean is ", sum(myList) / len(myList))
# Option 3: Display the median
def option3(myList):
sortedlist = sorted(myList)
if len(sortedlist) % 2:
median = myList[int(len(sortedlist) / 2)]
else:
center = int(len(sortedlist) / 2)
median = sum(myList[center-1:center+1]) / 2
print("The median is", median)
# Option 4: Print the list/array
def option4(myList):
print(sorted(myList))
# Option 5: Print the list/array in reverse order
def option5(myList):
print(sorted(myList, reverse=True))
main()
How I would do this:
The first part of the following code are a set of constants to customize the style of the menu. Then a set of functions representing each option are defined. The following 3 functions should not be modified, they generate the menu, display it and close the application. Then the main section starts, where you need to pass every option as an argument to setOptions(). The rest should not be modified either as it is the main loop.
# Menu formatting constants
MENU_HEADER = "Please choose an option:"
MENU_FORMAT = " * {:2}. {}"
MENU_QUIT_S = "Quit"
MENU_ASK_IN = "Enter option: "
MENU_INT_ER = "ERROR: Invalid integer. Please select again."
MENU_OPT_ER = "ERROR: Invalid option. Please select again."
END_MESSAGE = "Thanks for playing!"
# OPTIONS FUNCTIONS START HERE
def addElement(l):
""" Add a number to the list/array. """
n = -1
while n < 0:
try:
n = int(input("Enter a non-negative integer: "))
except ValueError:
print("It needs to be an integer.")
n = -1
else:
if n < 0:
print("It needs to be a non-negative integer.")
l.append(n)
def mean(l):
""" Calculate the mean. """
print("Mean: {:7.2}".format(sum(l) / len(l)))
def median(l):
""" Calculate the median. """
l = sorted(l)
p = int(len(l) / 2)
print("Median: {:7.2}".format(l[p] if len(l)%2 else sum(l[p-1:p+1])/2))
def oprint(l):
""" Print the list/array. """
print(sorted(l))
def rprint(l):
""" Print the list/array in reverse order. """
print(sorted(l, reverse=True))
# OPTIONS FUNCTIONS END HERE
def onQuit(l):
""" Function to execute when quitting the application. """
global quit
quit = True
print(END_MESSAGE)
def setOptions(*args):
""" Generates the menu and the options list. """
# Menu header and quit option (option 0)
menu = [MENU_HEADER]
options = [onQuit]
# Passed arguments represent texts and functions of additional options
for i, f in enumerate(args, start=1):
menu.append(MENU_FORMAT.format(i, f.__doc__.strip()))
options.append(f)
# We print the option 0 the last one
menu.append(MENU_FORMAT.format(0, MENU_QUIT_S))
# Returning both the menu and the options lists
return tuple(menu), tuple(options)
def displayMenu(menu):
""" Display the menu and get an option that is an int. """
while True:
for line in menu:
print(line)
try:
choice = int(input(MENU_ASK_IN))
except ValueError:
print(MENU_INT_ER)
else:
return choice
if __name__ == '__main__':
# Pass the option functions to the setOptions function as arguments
menu, options = setOptions(
addElement,
mean,
median,
oprint,
rprint
)
# Initiate the needed variables and start the loop
l = []
quit = False
while not quit:
c = displayMenu(menu)
try:
f = options[c]
except IndexError:
print(MENU_OPT_ER)
else:
f(l)
There is an indentation error inside your function addOne.
myList.append(num) is inside the while loop, and just before that you have a break, so the number is never appended to the list because we have left the loop already.