Allow user to choose option from menu with for loop - python

I'm working on part of a program which presents a menu of 3 options to the user. I want to allow the user to enter their menu choice (1-3) after which the menu appears again and allows the user to enter another choice and repeats this process for a total of n times which the user also inputs prior to the menu.
The program is just printing the menu 3 times in a row rather than in n separate iterations but I'm not sure how to fix this.
n = int(input('Please enter the number of iterations:'))
for i in range(0,n):
print('Enter 1 for choice 1\n')
print('Enter 2 for choice 2\n')
print('Enter 3 for choice 3\n')
choice = int(input('Enter your choice:'))
if (choice == 1):
....
....
else:
print('Invalid choice')

Put your code to handle the choice inside the loop:
n = int(input('Please enter the number of iterations:'))
for i in range(0,n):
print('Enter 1 for choice 1\n')
print('Enter 2 for choice 2\n')
print('Enter 3 for choice 3\n')
choice = int(input('Enter your choice:'))
if (choice == 1):
....
....
else:
print('Invalid choice')

Indent the following piece of code, 4 spaces to the right:
if (choice == 1):
...
...
else:
print('Invalid choice')
But if I may suggest a better implementation of what you are trying to do, then define a function which can handle a non-numeric user input, and in addition, take those prints outside the for loop:
def getUserInput(msg):
while True:
print msg
try:
return int(input(msg))
except Exception,error:
print error
n = getUserInput('Please enter the number of iterations:')
print 'Enter 1 for choice 1'
print 'Enter 2 for choice 2'
print 'Enter 3 for choice 3'
while n > 0:
choice = getUserInput('Enter your choice:')
if choice == 1:
...
n -= 1
elif choice == 2:
...
n -= 1
elif choice == 3:
...
n -= 1
else:
print 'Invalid choice'

Just for fun: I've rewritten this to introduce some more advanced ideas (program structure, use of enumerate(), first-class functions, etc).
# assumes Python 3.x
from collections import namedtuple
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError: # input string could not be converted to int
pass
def do_menu(options):
print("\nWhich do you want to do?")
for num,option in enumerate(options, 1):
print("{num}: {label}".format(num=num, label=option.label))
prompt = "Please enter the number of your choice (1-{max}): ".format(max=len(options))
choice = get_int(prompt, 1, len(options)) - 1
options[choice].fn() # call the requested function
def kick_goat():
print("\nBAM! The goat didn't like that.")
def kiss_duck():
print("\nOOH! The duck liked that a lot!")
def call_moose():
print("\nYour trombone sounds rusty.")
Option = namedtuple("Option", ["label", "fn"])
options = [
Option("Kick a goat", kick_goat),
Option("Kiss a duck", kiss_duck),
Option("Call a moose", call_moose)
]
def main():
num = get_int("Please enter the number of iterations: ")
for i in range(num):
do_menu(options)
if __name__=="__main__":
main()

You need to develop a python program that asks several intervals of integer numbers to the user
(negative or positive numbers). Each time, the user should have an option to either provide a new
interval or quit the program. The intervals will form lists of numbers and have a limit of -999 or 999.
An interval is defined as a continuous sequence of integer numbers. For every break in the continuity
of the integer numbers, you assume a new interval.

Related

How do I make a program keep repeating until I input a specific data that stops it?

I'm trying to make a program in python so that when I input a number from 1 to 10, a specific set of program goes on and asks for another number from 1 to 10 and runs another program, until I enter 0(zero) and the program stops.
So my guess was using a while loop but it didn't quite work out.
user_input = input()
user_input = int(user_input)
while user_input != 0:
(program)
else:
quit()
Try this:
user_input = int(input())
while user_input != 0:
(program)
user_input = int(input())
quit()
With your current code you only ask for input once so the loop won't end. This way you can input a new number after every iteration.
Your current program only asks once and then the loop keeps repeating. You need to keep asking for input inside the loop.
def program():
print("Executing Task....")
user_input = int(input())
while user_input != 0:
program()
user_input = int(input())
printf("Program Terminated")
Here it is:
def program():
pass
user_input = int(input())
while user_input:
program()
user_input = int(input())
quit(0)
A different way using iter with a sentinel:
def program(number):
if number < 0 or number > 10:
print('Invalid number:', number)
else:
print('Valid number:', number)
def quit():
print('quitting')
def get_number():
return int(input('Enter a number from 1 to 10: '))
for number in iter(get_number, 0):
program(number)
else:
quit()
not_zero = True
while not_zero:
num = int(input("Enter a number: "))
if num == 0:
not_zero = False
you can stop your loop using a boolean value.

How do I fix my Python function so that it returns with input prompts?

I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...

How to end the program (Python)?

I'm a newbie in Python3 coding and I have a problem here.
In line 14, I intended to end this program by printing "Thank you! Goodbye" at the part where you answer "n" to "try again?". However, it turned out that I would start all over again even if I've inserted "break" under it. Now, the only solution I can come up is to end the whole program with sys.exit(0), but I don't consider it an ideal solution since it just closes the whole program down.
import sys
while True:
x=int(input("Enter the coins you expected="))
f=int(input("Enter first coin="))
while f!=1 and f!=5 and f!=10 and f!=25:
print("invalid number")
f=int(input("Enter first coin="))
if x>f:
while x>f:
n=input("Enter next coin=")
if not n:
print("Sorry-you only entered",f,"cents")
again=input("Try again (y/n)?=")
if again=="y":
True
elif again=="n":
print("Thank you, goodbye!")
sys.exit(0)
break
while int(n)!=1 and int(n)!=5 and int(n)!=10 and int(n)!=25:
print("invalid number")
n=input("Enter next coin=")
f=f+int(n)
Replace your whole code with this:
import sys
Stay = True
while Stay:
x = int(input("Enter the coins you expected = "))
f = int(input("Enter first coin = "))
while f != 1 and f != 5 and f != 10 and f != 25:
f = int(input("Invalid number entered./nEnter first coin = "))
while x > f and Stay:
n = input("Enter next coin = ")
if not n:
print("Sorry, you only entered " + str(f) + " cents")
again = input("Try again (y/n)?=")
if again == "n":
print("Thank you, goodbye!")
Stay = False
if Stay:
n = int(n)
while n != 1 and n != 5 and n != 10 and n != 25:
print("Invalid number entered.")
n = int(input("Enter next coin = "))
f += n
I made your code more readable and fixed your problem by using a Boolean flag (Stay). This basically means that the program runs while Stay is True, and Stay becomes False when the user enters 'n'.

Python program not ending

Im a total python noob and Im trying to figure out why my program doesn't end when I input "0". It just starts the menu over again.
def menu():
print('\n\n\n\n')
print('List Processing Program Menu')
print('0 to exit')
print('1 to view data')
print('2 to append data')
while(1):
try:
choice = -1
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
except ValueError:
print('Enter an integer number for your menu selection')
return choice
def main():
while(1):
choice = menu()
if(choice == 0):
break
main()
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
Your problem is here. The while loop is broken out of and None is always returned (there is an implicit return of None at the end of every Python function).
You can clean up your code as follows:
def menu():
print('\n\n\n\n')
print('List Processing Program Menu')
print('0 to exit')
print('1 to view data')
print('2 to append data')
choice = None
while choice not in [0, 1, 2]:
try:
choice = int(input('Please enter a valid number choice '))
except ValueError:
print('Enter an integer number for your menu selection')
return choice
No value is ever returned from menu because your return statement is inside of the while loop that you break out of before you get to it. Hence, inside of your main, choice is always None.
If you de-indent the return statement this will work as you expect.
def menu():
print('\n\n\n\n')
print('List Processing Program Menu')
print('0 to exit')
print('1 to view data')
print('2 to append data')
while(1):
try:
choice = -1
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
except ValueError:
print('Enter an integer number for your menu selection')
return choice
def main():
while(1):
choice = menu()
if(choice == 0):
break
main()
If you want to be concise, you can remove all of your try/except statements because you never actually need to execute those anyhow.
def menu():
choice = -1
while choice < 0 or choice > 2:
choice = int(input('Please enter a valid number choice'))
return choice
def main():
choice = -1
while choice != 0:
choice = menu()
Right after the while (choice < 0 or choice > 2): loop you say break, but the return choice is inside of the while(1) loop. That means that your function will by implication return None, not choice. You just need to un-indent the return choice line.
Your menu() function returns None because your return statement is inside your while loop, which you break out of when the entry is valid.
Unindent your return statement so it lines up with while, or better yet, just return from inside the loop instead of using break.
You are never returning choice, because it is inside your first while loop. When you break out of that while loop, you just return None since there is no specific return specified. You have two options here:
Move the return outside of the while loop, or do something like this:
try:
choice = -1
while(choice < 0 or choice > 2):
return int(input('Please enter a valid number choice '))
except ValueError:
print('Enter an integer number for your menu selection')
You need to indent the break when you are reading the choice, or else your menu function will always return None.
try:
choice = -1
while(choice < 0 or choice > 2):
choice = int(input('Please enter a valid number choice '))
break
except ValueError:
print('Enter an integer number for your menu selection')

Ask the user if they want to repeat the same task again

If the user gets to the end of the program I want them to be prompted with a question asking if they wants to try again. If they answer yes I want to rerun the program.
import random
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
total = 0
final_coin = random.randint(1, 99)
print("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
total = total + user_input
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
while total != final_coin:
user_input = int(input("Enter next coin: "))
total = total + user_input
if total > final_coin:
print("Sorry - total amount exceeds", (final_coin))
if total < final_coin:
print("Sorry - you only entered",(total))
if total== final_coin:
print("correct")
You can enclose your entire program in another while loop that asks the user if they want to try again.
while True:
# your entire program goes here
try_again = int(input("Press 1 to try again, 0 to exit. "))
if try_again == 0:
break # break out of the outer while loop
This is an incremental improvement on the accepted answer:
Used as is, any invalid input from the user (such as an empty str, or the letter "g" or some such) will cause an exception at the point where the int() function is called.
A simple solution to such a problem is to use a try/except- try to perform a task/ code and if it works- great, but otherwise (except here is like an else:) do this other thing.
Of the three approaches one might try, I think the first one below is the easiest and will not crash your program.
Option 1: Just use the string value entered with one option to go again
while True:
# your entire program goes here
try_again = input("Press 1 to try again, any other key to exit. ")
if try_again != "1":
break # break out of the outer while loop
Option 2: if using int(), safeguard against bad user input
while True:
# your entire program goes here
try_again = input("Press 1 to try again, 0 to exit. ")
try:
try_again = int(try_again) # non-numeric input from user could otherwise crash at this point
if try_again == 0:
break # break out of this while loop
except:
print("Non number entered")
Option 3: Loop until the user enters one of two valid options
while True:
# your entire program goes here
try_again = ""
# Loop until users opts to go again or quit
while (try_again != "1") or (try_again != "0"):
try_again = input("Press 1 to try again, 0 to exit. ")
if try_again in ["1", "0"]:
continue # a valid entry found
else:
print("Invalid input- Press 1 to try again, 0 to exit.")
# at this point, try_again must be "0" or "1"
if try_again == "0":
break

Categories

Resources