How to create simple menu in Python with list functions? - python

Please have a look at the exercise that i was asked to do. I am struggling for hours now to make it work.
There has to be a menu with the following choices: add a number, remove number (enter placeholder), show list.
Each time choice is made program should ask if we want to re-run the script.
Tried loops, functions and it just doesn't seem to work with me.
See the code below.
Thank you in advance!
def list():
operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list
''')
mylist = []
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
else:
print('You have not chosen a valid operator, please run the program again.')
again()
def again():
list_again = input('''
Would you like to see main menu again? (Y/N)
''')
if list_again.upper() == 'Y':
list()
elif list_again.upper() == 'N':
print('OK. Bye bye. :)')
else:
again()
list()

You can use https://github.com/CITGuru/PyInquirer for than kind of menus.

As the others have pointed out, your mylist variable needs to be moved.
That said, I find that your mechanism of returning to the input query could be refined. See the code below. Here you keep everything in one function, without having to repeatedly ask the user if he/she would like to continue, it continues indefinately until you consciously break out of it.
def main():
mylist = []
while True:
operation = input('''
Select operation:
[1] Add number to the list
[2] Remove number from the list
[3] Display list
[4] Exit programm
''')
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
elif operation == '4':
break
else:
print("Invalid choice. Please try again.")
main()
Sidebar: "list" is a fixed expression in python. I would refrain from using it and others like it as variable names.

Verified Code
mylist = []
def list():
operation = input('''Select operation:\n [1] Add number to the list \n [2] Remove number from the list \n [3] Display list\n ''')
if operation == '1':
print("Type the number you would like to add to the list: ")
number = int(input())
mylist.append(number)
elif operation == '2':
print("Type position of the element number you like to remove from the list: ")
number = int(input())
mylist.pop(number)
elif operation == '3':
print(mylist)
else:
print('You have not chosen a valid operator, please run the program again.')
again()
def again():
list_again = input('''Would you like to see main menu again? (Y/N)''')
if list_again.upper() == 'Y':
list()
elif list_again.upper() == 'N':
print('OK. Bye bye. :)')
else:
again()
list()
Cheers!

Try moving mylist = [] outside of the function.

Related

Python not summing list correctly

Python is not summing all items in the list. What did I do wrong?
I'm trying to make a program that calculates the average of inputed numbers and it seems like the len() is working correctly but sum() is only summing some numbers.
numbers = []
More = True
while More:
xInp = input('Number: ')
yInp = input('Again?(y/n) ')
if yInp == 'y':
numbers.append(int(xInp))
elif yInp == 'n':
break
print(sum(numbers))
print(len(numbers) + 1)
print(sum(numbers) / int(len(numbers) + 1))
The problem is the order, you are exiting the program without considering the last value being input. Altering the order a bit will help you solve the issue. Furthermore be careful with apostrophes and doble apostrophes, I've edited that in the answer too, as it will return a SyntaxError otherwise:
numbers = []
while True:
xInp = input('Number: ')
numbers.append(int(xInp))
yInp = input('Again?(y/n) ')
if yInp == 'y':
pass
elif yInp == 'n':
break
print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))
Your code will only add the most recently-entered number to the array if the user selects y at the next prompt. Once they enter n, the last number entered is not appended to the list.
You need to append the number right after it has been entered, then check if the user wants to add more.
numbers = []
while True: # No need for a variable here
xInp = input("Number: ")
numbers.append(int(xInp))
yInp = input("Again? (y/n): ")
if yInp == "y":
pass
elif yInp == "n":
break
print(sum(numbers))
By convention, variables start with lowercase letters. Uppercase first letters are for class definitions (not instances). I had originally changed More to more, but as mentioned in the comments, it is not even necessary, so I replaced it with while True.
You missed the last value in more than one values.
numbers = []
More = True
while More:
xInp = input('Number: ')
yInp = input('Again?(y/n) ')
if yInp == 'y':
numbers.append(int(xInp))
elif yInp == 'n':
if xInp:
numbers.append(int(xInp))
break
print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

Trying to have a Python program quit with the letter "q", but input is an integer? [duplicate]

This question already has answers here:
Loop until a specific user input is received in Python [duplicate]
(3 answers)
Closed 4 years ago.
A quick snippet of the code below. I tried messing around with another answer posted on here, but it didn't seem to work at all. I'm not sure what I'm doing wrong. Using Python 3 on Xubuntu 18.04 LTS. Here's the code:
while True:
try:
print("Your room is DARK, yet a light flashes red. What do you do?")
print("")
print("1. Look around.")
print("2. There's a lamp somewhere...")
print("3. Go back to bed.")
print("")
ans = int(input(">>> "))
if ans == 1:
print("")
print("Too dark to see... better find a light...")
time.sleep(2)
if ans == 2:
print("")
print("Fumbling, you turn on your nightstand lamp...")
break
if ans == 3:
print("")
print("You sleep away the troubles... but you can't stay asleep...")
time.sleep(1)
print("")
print("Back to the world of the living...")
if ans == str('q'):
sys.exit(0)
except ValueError:
print("")
So, when the user inputs "q", I want the program to close. I can't seem to get it to do it at all.
The problem is with your line where you say int(input(">>> ")) which is converting what the user enters to an integer each time. What you should do is take in the user input as a string and then check if it is a valid number for 1, 2, & 3 or if it equals q.
Example:
ans = input(">>> ")
if ans == '1':
# Do something
elif ans == '2':
# Do something
elif ans == '3':
# Do something
elif ans == 'q':
sys.exit(0)
You're typecasting the q to an integer at input: ans = int(input(">>> ")) and then trying to typecast it back to a string at if ans == str('q'): Better solution would be to keep the input as a string in ans (remove the int() typecast and explicitly typecast it as an int with int() in each case.
Update: My original solution was wrong. The corrected one asks if the string is a digit and then evaluates it as an int. This is more verbose and I therefore recommend Karl's solution. But in case you're wedded to typecasting the string as an int I'm leaving this posted.
while True:
try:
ans = input(">>> ")
if ans.isdigit() and int(ans) == 1:
...
elif ans.isdigit() and int(ans) == 2:
...
elif ans.isdigit() and int(ans) == 3:
...
elif ans == 'q':
sys.exit(0)
except ValueError:
print("")
Then you don't even need to call str() at all.

error when validating user input

I'm trying to create a menu-driven program that will generate 5 random integers between 0 and 9, and store them in a List. I want it to then allow the user to enter an integer and then search the List, reporting on the location of the integer in the List (if found) or -1 if not. Then display the result of the search to the screen and re-display the menu.
def main():
choice = displayMenu()
while choice != '4':
if choice == '1':
createList()
elif choice == '2':
print(createList)
elif choice == '3':
searchList()
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = input("Enter option-->")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print("Invalid option. Please select again.")
return myChoice
import random
def linearSearch(myList):
target = int(input("--->"))
for i in range(len(myList)):
if myList[i] == target:
return i
return -1
#This will generate the five random numbers from 0 to 9
def createList():
newList = []
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
for i in range(5):
newList.append(random.randint(0,9))
return newList
#Option two to display the list
def displayList():
myList = newList
print("Your list is: ", newList)
#Option 3 to search the list
def searchList():
target = int(input("--->"))
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
However when it prompts the user for the five numbers it says invalid no matter what you enter. Could someone please give me an example on how I could fix this?
Careful with your input parsing. Either leave input as a string and deal with strings, or initially cast it to an int and continue dealing with ints.
myChoice = str(input())
# input 1
if myChoice in ['1', '2', '3', '4']:
print(myChoice)
or
myChoice = int(input())
# input 1
if myChoice in [1, 2, 3, 4]:
print(myChoice)
In createList, you are taking the input twice then referring to an undefined variable a
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
...
if any([num < 0 for num in a]):
Exception
should be something like
text_input = input("Give me five numbers: ")
numbers = [int(num) for num in text_input.split(' ')]
if any([num < 0 for num in numbers]):
raise ValueError
Your programme has a number of other oddities, but perhaps you're still working on these:
You don't do anything with the numbers you have input in createList but instead return a list of random numbers. Your description also suggests you want a list of random numbers, so why are you inputting the numbers in the first place?
You make variables myList and newList but your functions won't be able to access these unless you declare them as global or explicitly pass them as parameters
linearSearch can be written more simply using list.index:
.
def linearSearch(myList, target):
if target in myList:
return myList.index(target)
else:
return -1
OK - I found logical and syntax errors at multiple places. I will try to list them as possible.
Commented out redundent block of choices in displayMenu() function.
fixed main() function. You were not catching values/list returned by
functions
Defined myList as global list that needed to be passed
linearSearch(myList,target) had extra user input and tweaked logic
to work. It was only working for finding number at first index.Ideally you can use list.index(value) method to get index #
Commented out extra loop in createList() function
Tweaked functions to receive global list to work properly.
I've tweaked your code as little as possible. Commented out lines not required.
I believe it works as intended.
Working Code:
def main():
myList = []
choice = displayMenu()
while choice != '4':
if choice == '1':
myList =createList()
elif choice == '2':
#print(myList)
displayList(myList)
elif choice == '3':
searchList(myList)
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = str(input("Enter option-->"))
"""
if myChoice != 1 and myChoice != 2 and \
myChoice != 3 and myChoice != 4:
print("Invalid option. Please select again.")
"""
return myChoice
import random
def linearSearch(myList,target):
#target = int(input("--->"))
found = False
for i in range(len(myList)):
if myList[i] == target:
found = True
return i
if found == False:
return -1
#This will generate the five random numbers from 0 to 9
def createList():
print "Creating list..............."
newList = []
"""
while True:
try:
num = input("Give me five numbers: ")
num = [int(num) for num in input().split(' ')]
print(num)
if any([num < 0 for num in a]):
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
"""
for i in range(5):
newList.append(random.randint(0,9))
#print newList
return newList
#Option two to display the list
def displayList(myList):
#myList = newList
print("Your list is: ", myList)
#Option 3 to search the list
def searchList(myList):
target = int(input("--->"))
#print("Searching for" , target)
result = linearSearch(myList,target)
if result == -1:
print("Not found...")
else:
print("Found at", result)
main()
Output
>>>
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->1
Creating list...............
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->2
('Your list is: ', [1, 4, 6, 9, 3])
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->4
('Found at', 1)
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->9
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->10
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->3
--->10
Not found...
Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
Enter option-->4
Thanks for playing!
>>>
Final notes,
You may want to start with something simple such create a menu that prints different sentences for different choices to see if it works and then go as complex as you wish.
Change
myChoice = input("Enter option-->")
to
myChoice = str(input("Enter option-->"))
Function input returns an integer, and comparison with str will allways return False.

Creating a list of five numbers

I'm trying to have Python prompt the user to pick five numbers and store them in the system. So far I have:
def main():
choice = displayMenu()
while choice != '4':
if choice == '1':
createList()
elif choice == '2':
print(createList)
elif choice == '3':
searchList()
choice = displayMenu()
print("Thanks for playing!")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' and myChoice != '4':
print ("""Please choose
1. Create a new list of 5 integers
2. Display the list
3. Search the list
4. Quit
""")
myChoice = input("Enter option-->")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4':
print("Invalid option. Please select again.")
return myChoice
#This is where I need it to ask the user to give five numbers
def createList():
newList = []
while True:
try:
num = (int(input("Give me five numbers:")))
if num < 0:
Exception
print("Thank you")
break
except:
print("Invalid. Try again...")
for i in range(5):
newList.append(random.randint(0,9))
return newList
Once I run the program it allows me to choose option 1 and asks the user to enter five numbers. However if I enter more than one number it says invalid and if I only enter one number it says thank you and displays the menu again. Where am I going wrong?
numbers = [int(x) for x in raw_input("Give me five numbers: ").split()]
This will work assuming the user inputs the numbers separated by blank spaces.
Use raw_input() instead of input().
With Python 2.7 input() evaluates the input as Python code, that is why you got error. raw_input() returns the verbatim string entered by the user. In python 3 you can use input(), raw_input() is gone.
my_input = raw_input("Give me five numbers:") # or input() for Python 3
numbers = [int(num) for num in my_input.split(' ')]
print(numbers)
#DmitryShilyaev has properly diagnosed the problem. If you want to read 5 numbers in a single line, you could use split to split the string that input returns, and convert each element of that list to an int.

Returning to menu after command? Python

I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def animalmenu():
print()
print()
print()
print()
print('Welcome to the menu. I am thinking of a menu. Select the option\'s below to try and guess my animal.')
print()
print('a) No. of Legs')
print('b) Type of animal')
print('c) Preffered Climate')
print('d) Size')
print('e) Colour')
print('f) Diet')
print('g) Habitat')
print('h) Can be kept as pet')
print('i) Guess animal')
print()
print('When in a menu, type in \'555\' to return here')
AniChoice = input('Choose your option: ')
if AniChoice == 'a':
loop = 10
while loop == 10:
print()
print('')
print()
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
print('r = Return to menu, g = guess again.')
rg = input()
if rg == 'g':
print('Loading...')
elif rg == 'r':
loop = 0
time.sleep(1)
print('Returning to menu...')
time.sleep(1)
animalmenu()
everytime I run it, I type in a number as the code asks but then, instead of asking if I want to return to the menu it just asks the question again and again, 'Guess the number of legs: '. I know this is something to do with my looping method but I do not understand and because of the integer setting I cannot just make another if, like so:
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
elif guessleg == 'back':
loop = 0
animalmenu()
And I do not see any other way of doing it as neither way seems to work? How would you suggest returning to animalmenu()?
As the message is telling you, 'back' is not an integer, but you are comparing it to a variable into which you have put an integer value. Specifically, your line:
guessleg = int(input('Guess the number of legs: '))
puts an integer value into guessleg (or more properly tries to) from the user's input.
One approach to resolve this is to capture the user's input in a string variable, compare that string to 'back' first, and then convert to an integer if needed.
Another approach is to wrap a try/except around the integer conversion and proceed with the integer check if the conversion is successful and with the check against 'back' if the exception is encountered. This is probably preferred these days and I've put it into code:
inp_val = raw_input('Guess the number of legs: ')
try:
guess_num = int(inp_val)
if guess_num == leg:
print('True')
else:
print('False')
except ValueError:
if inp_val == 'back':
loop = 0
else:
print 'Invalid entry'
animalmenu()
because the you convert your input into integer and store it into guessleg which means guessleg is also an integer. However, 'back' is a string. You can't compare the string with integer. the 3 == 'back'means nothing.
and syntax error may because of your indent.
UPDATE:
if you want to return to the top menu, you can do something like:
def animalmenu():
while True:
print your menu here
and do something....
while ...:
get input and do something...
if get the input of 'back to menu':
break
UPDATE again:
I don't think you shall use input() here, try readline() or raw_input() instead.

Categories