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
Related
This is my code :
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
When I input either a or b, it just asks me to "Enter A or B" again. It doesn't go to the functions its supposed to.
Any idea why is this?
The code is perfect, except a redundant else, as mentioned in the comment. Are you entering a (a + space) rather than simply a (a without space) ? The problem is in the input that you are providing and not in the code!
def chooseReport():
print "Choose a report."
t=True # t starts at true
while t:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
t=False # t turns false to break out of loop
elif choice == 'b' or choice == 'B':
reportB()
t=False
Try this. It keeps looping when t is true and stops when t is false. The problem might also be in reportA or reportB or how you are calling chooseReport.
The problem is in the raw_input(). It returns a string but maybe this string is "a " or "a\n" though you have entered "a" or "b".
I would do this:
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if "a" in choice or "A" in choice:
reportA()
break
elif "b" in choice or "B" in choice:
reportB()
break
else:
continue
Tried your code in the following script, it works fine both on Linux and on Windows.
def reportA():
print "AAAAA"
def reportB():
print "BBBBB"
#Choose Report
def chooseReport():
print "Choose a report."
while True:
choice = raw_input("Enter A or B: ")
if choice == 'a' or choice == 'A':
reportA()
break
elif choice == 'b' or choice == 'B':
reportB()
break
else:
continue
chooseReport();
First, your code works fine, the most probably error is that you are writing a wrong input (e.g: with more characters). To solve that you could use "a" in choice or "A" in choice. But if it isn't working... keep reading.
It's seems that break isn't affecting the while loop, I don't have python 2 so I am not very sure why (in python 3 [after change raw_input to input and print to print()] your code works perfect). So you should use the condition of the while to break it.
while True work theorically for ever because each time the code is executed it checks the condition -True- and because it's true it keeps looping.
You could manipulate that condition in order to break the loop (don't allow execute again its code).
For example you could use this:
#Choose Report
def chooseReport():
print "Choose a report."
allow = True # allow start as True so the while will work
while allow:
choice = raw_input("Enter A or B: ")
if choice.lower().strip() == "a": # This is better. .lower() make "A" > "a", and .strip() delete " a " to "a", and "a/n" to "a".
reportA()
allow = False # allow now is False, the while won't execute again
elif choice.lower().strip() == "b":
reportB()
allow = False # allow now is False, the while won't execute again
# The else is complete redundant, you don't need it
Code is fine. I think you call your chooseReport() function in a loop or your input has extra characters and if conditions didn't satisfied.
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()
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.
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.
Sorry quite new to python in the grand scheme of things, basically I want to be able to have an input screen that users have a selection of choices, when a choice has been made a command will run, then give the user the option to go back to the choices to choose another one, or to exit the program completely.
Currently I have
print ("1.")
print ("2.")
print ("3.")
errorch=0
while not errorch :
try :
choice = int ( input('Please Choose from Options below :') )
errorch = 1
except ValueError as e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
if choice == 1:
print ("CODE:")
elif choice == 2:
print ("OTHER:")
elif choice == 3:
print ("OTHER:")
else:
print ("Invalid Choice. Please Try Again:")
k=input('Press close to exit')
In each choice I do have code that runs, but to save space I have omitted this
Use a while loop.
while True: # this loop runs forever
print("1.")
...
print("4.") # this is for exit
# get input
if choice == 1:
...
# if choice is 4, then break out of this loop
elif choice == 4:
break # breaks out of the loop
else:
...
You can just wrap the whole thing in another while loop:
while True:
...
if k.lower() == "close":
break
You can use this same form to make your existing loop neater, removing the errorch flag:
while True:
try:
choice = int(input('Please Choose from Options below :'))
except ValueError as e :
print ("'%s' is not a valid integer." % e.args[0].split(": ")[1])
else:
break