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

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()

Related

Function will not loop

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()

Can I create a function to break a while loops in python?

I am writing a program with python to simulate flipping a coin or rolling dice. The coin and dice use while loops to give the user the option to roll or flip again, an example is:
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
done = input("""would you like to roll again? Type y to roll again,
type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The problem I am having is that I would like to take every line starting from done and make it into it's own function that I can just insert into every function rather than typing the whole thing out again and again, like this.
def d4ing():
d4ing = True
while d4ing:
print(random.randint(1,4))
rerolling()
def rerolling():
done = input("""would you like to roll again? Type y to roll again, type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The error message I am getting:
SyntaxError: 'continue' not properly in loop
A break or a continue must be in a loop in its current scope. You cannot break a loop in the above scope from inside a function. Here is a general example of what raises the SyntaxError: 'break' outside loop error. The same holds for continue.
def break_up():
break # This is a syntax error
while True:
break_up()
Although, this is not a problem, since you can make the function return a value and conditionally break in the upper scope.
In your specific example though, you can also return whether or not you want to reroll by assigning the return value to d4ing.
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
d4ing = rerolling()
def rerolling():
done = input("Would you like to roll again?")
if done == "y":
return True
elif done == "d":
return False
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")

is a While True or If Statement best to execute one function before moving to the next

I am stuck on a simple issue. I am attempting to ask the user to choose a desired function from a list. This inputted user string will invoke the chosen function until it finishes running. (It is a lighting sequence). After this sequence ends, I would like to ask the user if he or she wishes to choose another function. If so, continue. If not, exit the code.
I cannot decide if a while true or if statement is the best to achieve this.
Here is my code:
# random functions
def rainbow():
print 'rainbow'
def clover():
print 'clover'
def foo():
print 'eggs'
if __name__ == '__main__':
# here are some random initializations
print 'ctr-c to quit'
user_input = input("choose from the following: ")
if user_input == 'rainbow':
print 'generating'
rainbow()
rainbow()
rainbow()
user_input = input('choose another')
if user_input == 'foo':
clover()
clover()
I would suggest using a while loop here until you get a successful user_input, upon which you'll want to break the loop. Inside the while look you can have your if statements as needed. For example, in your above code, what happens if the user types in "rainboww", it basically just exits the program. It'd be better to have it like this:
while True:
user_input = input('...')
if "good result"
break
else:
continue
while True:
user_input = input("choose from the following: ")
if user_input == "condition a":
do something
elif user_input == "condition b":
do something..
elif any(user_input == keyword for keyword in ["q", "quit"]):
# when meet any quit keyword, use break to terminate the loop
break
else:
# when doesn't find any match, use continue to skip rest statement and goto the beginning of the loop again
continue
while True can meet your requirement. you can use if-elif-else clauses to do different works.

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

Why isn't this code repeating? Python 3.3

This is a code that I have used when repeating a sequence I have used but it doesnt seem to be working can anyone see any problems?The code is for a currency converter. Im using Python 3.3
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Edit,This is the rest of the code:
if userChoice == "1":
userUSD = float(input("Enter the amount of USD you wish to convert.\n"))
UK = userUSD * 0.62
print("USD", userUSD, "= ", UK, "UK")
elif userChoice == "2":
UK = float(input("Enter the amount of UK Currency you wish to convert.\n"))
userUSD = UK * 1.62
print("UK", UK, "= ", userUSD, "USD")
def doagain():
userDoAgain = raw_input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Generally speaking, using recursion to handle a repeated control flow in Python is a bad idea. It's much easier, and less problematic to use loops instead. So, rather than defining a function doagain to ensure you get an answer to your question about running again, I suggest using a while loop. For the larger function that you'll be repeating, I suggest using a loop as well.
def repeat_stuff():
while True: # keep looping until told otherwise
# do the actual stuff you want to do here, e.g. converting currencies
do_stuff_once()
while True: # ask about doing it again until we understand the answer
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain.lower() == "yes":
break # go back to the outer loop
elif userDoAgain.lower() == "no":
print("Thank you for using this program")
return # exit the function
else:
print("Error: You entered invalid information.")
Note that I've changed the checks of the yes/no input strings to be case insenstive, which is a rather more user friendly way to go.
You are using recursion (the function calls itself) while it may be much nicer to just wrap the code you want to repeat in a while loop.
Example of this usage:
userContinue = "yes"
while (userContinue == "yes"):
userInput = input("Type something: ")
print("You typed in", userInput)
userContinue = input("Type in something else? (yes/no): ").lower()
Probably you need to use the function "raw_input" instead of only input.

Categories