I want my if function to keep repeating on python when it falls onto else. How do I do that? I've added an example of my code.
if selection1 == "C":
print("Ok")
elif selection1 == "E":
print("Ok")
elif selection1 == "Q":
print("Ok...") quit()
else:
selection1 == print("The character you entered has not been recognised, please try again.")
I don't know whether you meant this but this program does exactly as what your question asks
while True:
selection1 = input("Enter Character\n")
if selection1 == "C":
print("Ok")
elif selection1 == "E":
print("Ok")
elif selection1 == "Q":
print("Ok...")
break
else:
selection1 == print("The character you entered has not been recognised, please try again.")
The program takes in characters as inputs and checks them with the hardcoded characters. If not matched it will ask for the user to repeat until the letter Q is matched. An output can be
Enter Character
C
Ok
Enter Character
E
Ok
Enter Character
v
The character you entered has not been recognised, please try again.
Enter Character
Q
Ok...
Here are two possible approaches
while True: # i.e. loop until I tell you to break
selection1 = GetSelectionFromSomewhere()
if selection1 == 'C':
print('Okay...')
break
elif selection1 == 'E':
print('Okay...')
break
elif selection1 == 'Q':
print('Okay...')
quit()
else:
Complain()
Some purists dislike while True loops because they don't make it explicit what the looping condition is at first glance. Here's another listing, which has the advantage of keeping break statements and other housekeeping out of your if cascade, so you can focus on the necessary actions there:
satisfied = False
while not satisfied:
selection1 = GetSelectionFromSomewhere()
satisfied = True
if selection1 == 'C':
print('Okay...')
elif selection1 == 'E':
print('Okay...')
elif selection1 == 'Q':
print('Okay...')
quit()
else:
Complain()
satisfied = False
while selection1 != "Q":
if selection1 == "C":
print "Ok"
elif selection1 == "E":
print "Ok"
else:
print " Chose again"
print "quit"
quit()
while True:
n = raw_input("\nEnter charachter: ")
if n == "C" OR n=="E" OR n=="Q":
print("Ok !")
break # stops the loop
else:
n = "True"
characters = {'C','E','Q'}
def check():
ch=raw_input("type a letter: ")
if ch == q:
quit()
print "ok" if ch in characters else check()
check()
But you have already your answer from the previous posts. This is just an alternative.
Related
I was working with a mastermind assignment but one of my define function isn't working as expected.
How do I make the "quit" jump back to "have a guess..." instead of continue to the colourlst?
def valid_usercolour():
while True:
#print('Welcome to the Mastermind')
usercolour = input('Please have your guess [r,o,y,g]: ').lower()
if 'quit' in usercolour:
while True:
dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
if dc_quit.lower() == "y":
print()
print('Alright, thank You for playing, Goodbye', user_name, '!' )
quit()
break
elif dc_quit.lower() == "n":
print("Alright, let's continue to our game")
break
else:
print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
continue
colourslist = ['r','o','y','g']
if any(character not in colourslist for character in usercolour):
print("Error! Only Characters ,", colourslist, "are allowed")
continue
if len(usercolour) != 4:
print("Error! Only 4 characters are allowed!")
continue
break
return usercolour
Just add else: and indent what's below it right before colourslist. Python codes do not "jump back":
def valid_usercolour():
while True:
#print('Welcome to the Mastermind')
usercolour = input('Please have your guess [r,o,y,g]: ').lower()
if 'quit' in usercolour:
while True:
dc_quit = input('Do you really wanted to quit the game?[y/n]: ')
if dc_quit[0].lower()[0] == "y":
print()
print('Alright, thank You for playing, Goodbye', user_name, '!' )
quit()
break
elif dc_quit[0].lower()[0] == "n":
print("Alright, let's continue to our game")
break
else:
print("Sorry! I don't understand what you mean, could you please type only [Y/N]")
continue
else:
colourslist = ['r','o','y','g']
if any(character not in colourslist for character in usercolour):
print("Error! Only Characters ,", colourslist, "are allowed")
continue
if len(usercolour) != 4:
print("Error! Only 4 characters are allowed!")
continue
break
return usercolour
BONUS: I added [0] at the values of dc_quit to force taking one character only. A full 'yes' or 'no' works too ;-)
I have written a menu that runs before I am testing it will only run the first if and not any of the following elif lines.
An example being when asked to make my input in the first question in the menu, if I type exit (or any capitalised variation) it will output 'Goodbye' as expected and stop running but if I type in 'color', 'colour', 'play' or make an invalid entry nothing happens and the script stops running.
print("Python Adventure\n")
def menu(): # This is the menu text for options before running the game
option_1 = input("Select an option:\nPlay Color Exit\nType:")
if option_1.lower() == "exit":
print("\nGoodbye")
exit()
elif option_1.lower() == "color" or "colour": # color options here
def color():
color_1 = input("Play with color? yes/no\nType:")
if color_1.lower() == "n" or "no":
print("Color off\n")
menu()
elif color_1.lower() == "y" or "yes":
print("Color on\n")
menu()
elif color_1.lower() != "":
print("Not recognised please try again.")
color()
color()
elif option_1.lower() == "play": # Text based game will start here.
print("Running: Python Woods")
elif option_1.lower() != "": # Invalid entry trigger.
print("Invalid entry, try again.")
menu()
menu()
Please feel welcome to correct me on any terminology and formatting too. Any learning is helpful.
Here is a better design, which most of the commenters have implied:
print("Python Adventure\n")
def color():
color_1 = input("Play with color? yes/no\nType:")
if color_1.lower() in ("n", "no"):
print("Color off\n")
elif color_1.lower() in ("y", "yes"):
print("Color on\n")
else:
print("Not recognised please try again.")
return True
return False
def menu(): # This is the menu text for options before running the game
option_1 = input("Select an option:\nPlay Color Exit\nType:")
if option_1.lower() == "exit":
print("\nGoodbye")
return False
elif option_1.lower() in ("color", "colour"): # color options here
while color():
pass
elif option_1.lower() == "play": # Text based game will start here.
print("Running: Python Woods")
elif option_1.lower() != "": # Invalid entry trigger.
print("Invalid entry, try again.")
return True
while menu():
pass
I have written a main script that has a menu with 5 different options, the fifth option is if the user wants to quit the program. If the user types 5 in the main menu the program is supposed to quit, but it doesn't... It just keeps on looping through the menu. Can anyone help me resolve this issue??
menuItems = np.array(["Load new data", "Check for data errors", "Generate plots", "Display list of grades","Quit"])
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
break
You have nested loops, and break only breaks out of the inner loop.
To remedy this delete the nested loop and the break from the else block:
while True:
choice = displayMenu(menuItems)
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
In your code, when you call break, it breaks from the inner while loop and goes to the outer while loop which causes the whole thing to go on again. If for some cases you want both of the while loops to break then you can use some sort of a flag.
Example,
flag = False
while True:
while True:
if (1 == var):
flag = True
break
if flag:
break
//Your code
flag = False
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
flag = True
break
elif (choice == 2):
checkErrors(grades)
flag = True
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
flag = True
break
else:
print("Invalid input, please try again")
flag = True
break
if True == flag:
break
I'm new to python programming and I'm having trouble selecting an option. I have created a menu for example I have :
Instructions
Catering
Packages
add
When the user selects i, c, a or p each menu will come up. However, if the user selects 'p' before 'a' then I need to set a prompt to select a first..
INSTRUCTIONS = "I"
CATERING = "C"
PACKAGES = "P"
def menu():
userInput = True
while userInput != False:
print("Instructions
Catering
Packages")
userInput = input(">>>")
if userInput == INSTRUCTIONS:
instructions()
elif userInput == CATERING:
Catering()
elif userInput == PACKAGES:
Packages()
else:
print("Error")
Thank you
Here is the Code in a Loop::
def menu():
while True:
u_in=raw_input("Input Here:: ")
u=u_in.lower()
if u_in=="":
continue
elif u=="i":
Instructions()
elif u=="c":
Catering()
elif u=="p":
Packages()
If you are using python2.x, use raw_input() instead of input().
def menu():
mybool == True
userInput = input("Instructions\nCatering\nPackages\n>>> ")
b = userInput.lower()[0]
if b == 'a':
mybool = True
elif b == 'i':
Instructions()
elif b == 'c':
Catering()
elif b == 'p':
if mybool == True:
Packages()
else:
input('Here is where we display a prompt! ')
else:
print("Error")
Basically, this sets a variable to be False, and then gets input. If the input is a, then we set myBool to be True. If the user selects p and myBool is True (a has already been selected), it carries on. Otherwise, it displays a prompt.
Here is a dumbed down version of my program that I am using as an example.
I know that using GOTO is bad practice, because it leads to sloppy and confusing code, however it would be perfect for solving this problem that I have (problem detailed at bottom of post).
def prompt():
while True:
user_input = raw_input:
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': ##Restart
???????????
else:
return user_input
load_word_list() ##Load words into list
for word in wordList: ##Loop that needs to restart
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer != word:
print "You got it wrong"
#Print results
At the Prompt, I want to reload the wordList list and restart the outer for loop.
With GOTO I could just put in place of ????... GOTO load_word_list().
But since this is Python (and Python is about good code), What is the Pythonic way to solve this problem?
You could return a tuple from prompt():
elif user_input == 'r': #Restart
return True, None
else:
return False, user_input
and
restart, answer = prompt()
if restart:
break
if answer != word:
print "You got it wrong"
Another take on jsbuenos solution. This actually does re-run the outer for loop.
def prompt():
while True:
user_input = raw_input()
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': #Restart
raise RestartException
else:
return user_input
class RestartException(Exception):
pass
while True:
load_word_list() ##Load words into list
try:
for word in wordList: ##Loop that needs to restart
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer != word:
print "You got it wrong"
except RestartException:
# catch the exception and return to while loop
pass
else:
# exit while loop
break
class RestartException(Exception):
pass
def prompt():
while True:
user_input = raw_input:
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': #Restart
raise RestartException
else:
return user_input
load_word_list() ##Load words into list
for word in wordList: ##Loop that needs to restart
try:
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer != word:
print "You got it wrong"
except RestartException:
pass
I don't undertand very much what you want to do, but you can remove the special case in prompt and handle the 'r' special case in the for loop directly
def prompt():
while True:
user_input = raw_input("enter words")
if input == '?':
print help_o
elif not user_input.isalpha():
print "You entered bad characters"
elif user_input == 'r': #Restart
return False
else:
return user_input
answer = True
while answer == True:
load_word_list() ##Load words into list
for word in wordList: ##Loop that needs to restart
for i in range(5):
to_speak = "Spell, %s" %word
subprocess.Popen(['espeak', to_speak])
answer = prompt()
if answer == False:
answer = True # reset for the while loop
break # break to while loop
elif answer != word:
print "You got it wrong"
print results