Function will not loop - python

Have to make a table that runs functions. I can run the functions once, but after being able to submit for another function the code ends.
def main():
menu()
option=int(input('What option do you choose? '))
if option==1:
rol()
if option==2:
bing()
if option==3:
return
else:
print('Please pick from the menu!')
menu()
option=int(input('What option do you choose? '))
How do I loop it so that after it goes through the options roll() and bingo(), and the menu is shown again, it actually goes through with the functions?

Here is the code so that it will loop forever:
def main():
while True:
print('Please pick an option from the menu!')
menu()
option = int(input('What option do you choose? '))
if option == 3:
return
if option == 1:
roll()
elif option == 2:
bingo()

Assuming your main function works the way it is just once, you can simpy run the loop externally
def main():
# your code ...
if __name__ == "__main__":
while True:
main()

Related

While loop stopping even if it's False?

I thought the logic of my while loop made sense, but it abruptly stops after the first loop.
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
valid = False
while valid == False:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
return choice
if choice ==1:
valid=True
display_modules_average_scores()
menu()
elif choice ==2:
valid=True
display_modules_top_scorer()
menu()
elif choice==0:
exist=True
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
If I enter 5, it does:
print("Invalid choice, please enter again")
choice=int(input("Enter choice:"))
But if I enter 5 again, it stops the program. What am I doing wrong?
if I enter 5 again, it stops the program
Because you have a return statement that immediate ends the function you're running within.
You seem to be trying to create an infinite loop. You can start with testing exit and invalid conditions with this. Note:choice will never equal an empty string
while True:
choice=int(input("Enter choice (0 to exit):"))
if choice == 1:
pass # do something
elif choice == 2:
pass # do something else
elif choice == 0:
break
else:
print("Invalid choice, please enter again")
print("Thanks")
To exit the loop, you can use break, which executes code after the loop. Use return to end the function, as mentioned. There is a difference
If you're running this loop inside of the menu() function, you do not need to actually call the menu function again. That's the point of the while loop
By defining the function we can perform this task easily with no code duplication.
The Below code calls the function inputchoice() and then the inputchoice() will check the value entered by the user and if there the value is not valid then the inputchoice will call itself and the process continues untill the user enter correct input.
def inputchoice():
choice=int(input("Enter choice: "))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice!")
choice = inputchoice()
return choice
def menu():
choice = inputchoice()
print(choice)
if choice ==1:
valid=True
print("Do something if Valid = True")
elif choice ==2:
valid=True
print("Do something if Valid = True")
elif choice==0:
valid=True
print("Do something if Valid = True")
menu() #implementing menu function
I prefer making a dictionary with your functions, keeps the code clean in my eyes.
Consider this code here:
def choice1():
return 'choice1'
def choice2():
return 'choice2'
def defaultchoice():
return 'default'
choicedict = {
'1': choice1,
'2': choice2
}
while True:
choice = input("Enter choice (0 to exit):") # maintain as str to avoid error!
if choice == '0':
break
value = choicedict.get(choice, defaultchoice)()
print(value)
Single Function Code
def menu():
choice=int(input("Enter choice:"))
if (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
print("Invalid choice, please enter again")
menu()
elif choice ==1:
print("Oh, its working")
menu()
elif choice ==2:
print("Oh, its working")
menu()
elif choice==0:
print("===============================================")
print("Thank you for using Students' Result System")
print("===============================================")
menu()
Hi i would use a while loop like this. It would seem from this assignment that we are from the same institution. This is what i use for my code, I hope this helps.
while True:
user_input = input("Enter choice: ")
if (user_input == "0"):
print("=====================================================")
print("Thank You for using Students' Result System")
print("=====================================================")
break
elif(user_input == "1"):
display_modules_average_scores()
elif(user_input == "2"):
display_modules_top_scorer()
else:
print("Invalid choice, please enter again")

Python main function loop with a menu function is not working?

I am currently a college student taking a python class. Our assignment is to create this program with functions. The main function calls the menu and then we write a loop in the main function to access the other functions based on the user response in the menu function.
I can't seem to get my loop to work. When I select a menu option nothing happens. For now, I just have print statements to test the calling of the functions. I want to make sure this works before I write the functions.
If anyone has an example of what the loop should look like to call the functions it would help me a lot.
def GetChoice():
#Function to present the user menu and get their choice
#local variables
UserChoice = str()
#Display menu and get choice
print()
print("Select one of the options listed below: ")
print("\tP\t==\tPrint Data")
print("\tA\t==\tGet Averages")
print("\tAZ\t==\tAverage Per Zone")
print("\tAL\t==\tAbove Levels by Zone")
print("\tBL\t==\tBelow Levels")
print("\tQ\t==\tQuit")
print()
UserChoice = input("Enter choice: ")
print()
UserChoice = UserChoice.upper()
return UserChoice
def PrintData():
print("test, test, test")
def AverageLevels():
print("test, test, test")
def AveragePerZone():
print("test, test, test")
def AboveLevels():
print("test, test, test")
def BelowLevels():
print("test, test, test")
def main():
Choice = str()
#call GetChoice function
GetChoice()
#Loop until user quits
if Choice == 'P':
PrintData()
elif Choice == 'A':
AverageLevels()
elif Choice == 'AZ':
AveragePerZone()
elif Choice == 'AL':
AboveLevels()
elif Choice == 'BL':
BelowLevels()
main()
The loop should start with the following:
while True:
Choice = GetChoice()
And the if conditions for the menu should follow at the same indent.
If you want to add an option to quit the program, add another elif statement as below:
elif Choice == "Q":
break
This will exit the loop and thus end the program.
(Excuse the many edits - using mobile)
You need to assign your Choice variable like so,
Choice = GetChoice()
Also, note that you can also delete line like this one,
UserChoice = str()
In python, you do not need to explicitly specify variables type.
And finally another small suggestion is to compare Choice.upper() to the values in the bottom of your code. This way, if someone enters 'p' it will still call PrintData()
You need to assign the return value of your GetChoice() function to the name Choice:
Choice = GetChoice()

Unable to enter if statement after raw_input

Whenever I call a function within a while loop in my project it will do absolute nothing according to the function just being called and will just continue to refresh the loop like nothing happened.
Here is a simple example I wrote demonstrating the problem. By running the code you will be shown a menu and you will need to enter a choice from the menu. When doing so a few "if" statements will check which option you chose and call and execute the code below them if the choice doesn't belong to any of the statements the menu will just refresh:
#!/usr/bin/env python
import os
import time
def test():
x = True
while True:
if not x:
print "You need to type 1\n"
choice = raw_input("type 1 here: ")
if choice == 1:
print 'Works!\n'
time.sleep(5)
break
else:
x = False
def test2():
print "Test123\n"
try:
while True:
os.system("clear")
menu_choice = raw_input("Enter Choice: ")
if menu_choice == 1:
test()
if menu_choice == 2:
test2()
if menu_choice == 3:
os.system("python")
except:
pass
As stated in the comments, raw_input returns a string and you'll need to cast it. BUT, you'd likely need to catch a ValueError for anything typed not a number.
Instead, you could do this
if choice == '1'
Same for menu_choice

Python menu-driven programming

For menu-driven programming, how is the best way to write the Quit function, so that the Quit terminates the program only in one response.
Here is my code, please edit if possible:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
while choice!="q":
if choice=="v":
highScore()
main()
elif choice=="s":
setLimit()
main()
elif choice=="p":
game()
main()
else:
print("Invalid choice, please choose again")
print("\n")
print("Thank you for playing,",name,end="")
print(".")
When the program first execute and press "q", it quits. But after pressing another function, going back to main and press q, it repeats the main function.
Thanks for your help.
Put the menu and parsing in a loop. When the user wants to quit, use break to break out of the loop.
source
name = 'Studboy'
while True:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choice = raw_input(">>> ").lower().rstrip()
if choice=="q":
break
elif choice=="v":
highScore()
elif choice=="s":
setLimit()
elif choice=="p":
game()
else:
print("Invalid choice, please choose again\n")
print("Thank you for playing,",name)
print(".")
def Menu:
while True:
print("1. Create Record\n2. View Record\n3. Update Record\n4. Delete Record\n5. Search Record\n6. Exit")
MenuChoice=int(input("Enter your choice: "))
Menu=[CreateRecord,ViewRecord,UpdateRecord,DeleteRecord,SearchRecord,Exit]
Menu[MenuChoice-1]()
You're only getting input from the user once, before entering the loop. So if the first time they enter q, then it will quit. However, if they don't, it will keep following the case for whatever was entered, since it's not equal to q, and therefore won't break out of the loop.
You could factor out this code into a function:
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=input(">>> ")
choice=choose.lower()
And then call it both before entering the loop and then as the last thing the loop does before looping back around.
Edit in response to comment from OP:
The following code below, which implements the factoring out I had mentioned, works as I would expect in terms of quitting when q is typed.
It's been tweaked a bit from your version to work in Python 2.7 (raw_input vs. input), and also the name and end references were removed from the print so it would compile (I'm assuming those were defined elsewhere in your code). I also defined dummy versions of functions like game so that it would compile and reflect the calling behavior, which is what is being examined here.
def getChoice():
print("\nMenu\n(V)iew High Scores\n(P)lay Game\n(S)et Game Limits\n(Q)uit")
choose=raw_input(">>> ")
choice=choose.lower()
return choice
def game():
print "game"
def highScore():
print "highScore"
def main():
print "main"
def setLimit():
print "setLimit"
choice = getChoice()
while choice!="q":
if choice=="v":
highScore()
main()
elif choice=="s":
setLimit()
main()
elif choice=="p":
game()
main()
else:
print("Invalid choice, please choose again")
print("\n")
choice = getChoice()
print("Thank you for playing,")
This is a menu driven program for matrix addition and subtraction
def getchoice():
print('\n What do you want to perform:\n 1.Addition\n 2. Subtraction')
print('Choose between option 1,2 and 3')
cho = int(input('Enter your choice : '))
return cho
m = int(input('Enter the Number of row : '))
n = int(input('Enter the number of column : '))
matrix1 = []
matrix2 = []
print('Enter Value for 1st Matrix : ')
for i in range(m):
a = []
for j in range(n):
a.append(int(input()))
matrix1.append(a)
print('Enter Value for 2nd Matrix : ')
for i in range(m):
a = []
for j in range(n):
a.append(int(input()))
matrix2.append(a)
choice = getchoice()
while choice != 3:
matrix3 = []
if choice == 1:
for i in range(m):
a = []
for j in range(n):
a.append(matrix1[i][j] + matrix2[i][j])
matrix3.append(a)
for r in matrix3:
print(*r)
elif choice == 2:
for i in range(m):
a = []
for j in range(n):
a.append(matrix1[i][j] - matrix2[i][j])
matrix3.append(a)
for r in matrix3:
print(*r)
else:
print('Invalid Coice.Please Choose again.')
choice = getchoice()

Except block always being thrown even after going through the try block and rest of the program?

I check to see if input can be changed into an integer if it can't it starts back from the beginning of UI(). I followed it through pycharm's debugger and it will pass the try, but when I try using 4 to exit.It will go through to the end, and then go back up to the except block.
I think the parts I commented after are the only relevant parts. Thanks for any help.
def UI():
global exitBool
global newBool
if not TV.tvList:
tv = TurnOnTV()
if TV.tvList:
l = list(TV.tvList.keys())
tv = TV.tvList.get(l[0])
print("1)change channel\n2)change volume\n3)Turn on another TV\n4)Exit\n5)Choose TV") #print accepted answers
choice = input()
try:
choice = int(choice) #try block and exception block
except:
print("\nInvalid Choice\n")
UI()
choice = int(choice)
if choice == 1:
if tv:
tv.changechannel(input("enter channel: "))
else:
print('sorry no tvs are available\n')
elif choice == 2:
if tv:
tv.changevolume(input("Enter in volume: "))
else:
print('Sorry no Tvs available')
elif choice == 3:
TurnOnTV()
elif choice == 4:
exitBool = True # exit bool to exit main loop
elif choice == 5:
tv = ChooseTV(input("Enter in TV name: "))
else:
print("Invalid Choice")
if tv:
tv.display()
def Main():
while exitBool == False: #Main Loop
UI()
When you catch the error and print "invalid choice" you must not call UI() again. That way you are making a recursive call, and when the inner UI() terminates the code goes on on the outer one.
Use a "while" statement to repeat a block of code until the user makes a valid choice.

Categories