python else: do nothing - python

I would like my program to no nothing if user selects option in menu that does not exist.
def mainMenu():
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
selection=str(raw_input(""))
if selection=='1':
some super-interesting things
if selection=='2':
Kim Kardashian with Eskimo riding a polar bear
else:
literally DO NOTHING, no changes, no exiting the program, just takes the input and waits for another command
mainMenu()
How to achieve that? 'pass' or 'return' causes to exit the program.
'mainMenu()' causes refreshing menu "page"

I would just use a loop that keeps waiting for valid input. It requests the input and if it's not one of the valid options it will keep waiting input.
def mainMenu():
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
valid_options = ['1', '2']
while True:
selection = str(raw_input(""))
if selection in valid_options:
break
if selection == '1':
some super-interesting things
elif selection == '2':
Kim Kardashian with Eskimo riding a polar bear
mainMenu()
You could even add an else statement in the if inside the loop to request the user for a valid option.

Erasing the else statement should do the job:
def mainMenu():
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
selection=str(raw_input(""))
if selection=='1':
some super-interesting things
if selection=='2':
Kim Kardashian with Eskimo riding a polar bear
mainMenu()
Anyway, I understand this is far from a final code, obviously the code inside if conditions won't work. If you want the code to ask again, it should be inside a loop, otherwise, the program will end. It should look like this:
def mainMenu():
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
selection = '0'
while selection != '1' or selection !='2':
selection=str(raw_input(""))
if selection=='1':
some super-interesting things
if selection=='2':
Kim Kardashian with Eskimo riding a polar bear
mainMenu()

A 'pass' or 'return' statement doesn't actually "exit the program", it exits the function. Now since there's nothing else in your program, it also ends up exiting the program, but this is not by itself due to those statements.
If your goal is to have the mainMenu function "restarting" when selection is neither 1 nor 2, you need a loop:
def mainMenu():
while True:
os.system("clear")
print("menu")
print("1 - option 1")
print("2 - option 2")
# you need to leave a way for the user
# to exit the program
print("0 - exit")
# raw_input already returns a string,
# but you may want to remove unwanted whitespace chars
selection = raw_input("").strip()
if selection == '0':
return
elif selection == '1':
some_super_interesting_things()
elif selection == '2':
KimKardashian().with(Eskimo()).riding(a_polar_bear)
else:
# no strictly needed but the users will appreciate...
print("sorry, {} is not a valid choice".format(selection))
# this prevents this code from being executed if you
# try to import your script as a module
if __name__ == "__main__":
mainMenu()

Related

while loop, asking user if he wants to repeat the program problem

So I have this while loop which asks user if he/she wants to repeat the program. All works good but I was trying it out and found out that after user repeats the program and when asked second time if he/she wants to repeat, I choose no. But the program still repeats although it prints that program is closing, how can I fix this?
edit: I've fixed it with changing break with return and adding return after main()
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
This is because main() function is being called recursively & endFlag is a local variable.
So when you first put 'y' , then another main() is recursively called from the first main() function.
After you put 'n' which ends this second main() and return to the first main which still in a loop with endFlag (local variable) with value as false.
So, need to change,
Either
endFlag variable as global ( i.e. defined outside main function )
Or,
some program exit function in place of break
The thing is that you're doing recursion over here, i.e. you're calling method main() inside main() and trying to break out of it the way you've done is not gonna work (well, you're know it :) )
Second - you don't need a forever loop inside a first loop, you can do it with one simple loop and break.
Here it is:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
this is what you should do:
(BTW this is a piece of example code)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(Im not sure if i put the indents correctly )
You can apply this concept into your code.

Code end up in an endless loop. Can't see why

I am working on a simple function to let the user select the language.
But for some reason, I can't see my mistake and the while loop never breaks.
def chooseLanguage():
"""Simple function to let the user choose what language he wants to play in"""
if game["language"] == "en_EN":
import res.languages.en_EN as lang
elif game["language"] == "de_DE":
import res.languages.de_DE as lang
else:
while game["language"] is None:
print ("Hello and welcome! Please select a language.")
print ("1. German / Deutsch")
print ("2. English")
langC = input ("Your choice: ")
if inputValidator(1, langC) == 1:
game["language"] = "de_DE"
break
elif inputValidator(1, langC) == 2:
game["language"] = "en_EN"
break
if game["language"] is None:
chooseLanguage()
else:
pass
Evidently the infinite loop was caused by inputValidator returning a value that was neither equal to 1 or 2. Thus the exit conditions of the loop were never met. And so it continues.

Python dictionary becomes empty as soon as the function, which added items to it, finishes execution

I am trying to write a menu in which option 1 would add a key:value pair to a dictionary and option 2 would run a threading module using the items from the dictionary. Key is a message from the user input and Value is a number of seconds, from the user input, that a thread should pause for, before displaying the message.
Threading itself is irrelevant right now though. What I'm struggling with is the fact that when I use the function for option 1, it adds the key:value pairs to the dictionary (called messages_and_times) successfully. But as soon as the function is finished the dictionary becomes empty again, as can be seen from the function for option 2, which accesses it.
At the bottom you can see my code. I've added the following lines in order to check what's in the dictionary at each step:
print(dict(messages_and_times))
if not messages_and_times:
print("This dictionary is empty.")
else:
print("This dictionary contains items.")
It doesn't seem to work correctly either however. First of all it prints "This dictionary contains items." whether the printed dictionary looks empty or not. Second of all the following part of my code (clear() is used for clearing the terminal display):
def create_dictionary():
clear()
answer = input(
"Would you like to add another message? (yes/no)").lower()
if answer == "yes":
option_1()
elif answer == "no":
clear()
print("You will now be returned to the main menu.")
print(dict(messages_and_times))
does print a dictionary containing items if I chose to add them. But if I add the line
print(dict(messages_and_times))
to the main_menu() itself, the above mentioned create_dictionary() function prints an empty dictionary instead. Just this one print() statement in the main_menu() affects whether create_dictionary() shows a dictionary with items in it or not.
Could someone please help me understand how to design a code in which the dictionary retains the items created by one function, so that they can be accessed by other functions?
Thank you in advance for your time and assistance,
import os
clear = lambda: os.system('cls')
def main_menu():
list_of_messages = []
list_of_times = []
messages_and_times = zip(list_of_messages, list_of_times)
def option_1():
clear()
list_of_messages.append(
input("Please type in a message you would like to add to the list:"))
clear()
list_of_times.append(
input("Please type in the time of delay for this message:"))
def create_dictionary():
clear()
answer = input(
"Would you like to add another message? (yes/no)").lower()
if answer == "yes":
option_1()
elif answer == "no":
clear()
print("You will now be returned to the main menu.")
print(dict(messages_and_times))
if not messages_and_times:
print("This dictionary is empty.")
else:
print("This dictionary contains items.")
time.sleep(1.5)
main_menu()
else:
clear()
print("Please answer yes or no.")
time.sleep(1.5)
create_dictionary()
create_dictionary()
def option_2():
clear()
print(dict(messages_and_times))
if not messages_and_times:
print("This dictionary is empty.")
else:
print("This dictionary contains items.")
time.sleep(5)
main_menu()
clear()
selection = 0
while selection == 0:
print(("-" * 15) + "MAIN MENU" + ("-" * 15) + "\n")
print("1: Input a message and a corresponding time of delay before its display.")
print("2: Print your customized list of messages.")
print("3: Generate a list of random messages with random delays.\n")
selection = int(input(
"Please select one of the options, by typing in the corresponding number:"))
if selection == 1:
option_1()
elif selection == 2:
option_2()
elif selection == 3:
clear()
print("You've selected the third option.")
else:
clear()
print("Please select from options 1 - 3.\n")
time.sleep(1.5)
main_menu()

Create a text menu in Python3x that is always available

I am new to python and learning quickly. Thank you all for the help.
I am attempting to create a text menu that will always run in the background of a storytelling text rpg. I have searched and cannot find an explanation of how to create an "always on" menu or how one would work.
I would like the player to be able to hit "m" at any time in the game and have the menu prompt show up.
So far, I have created a "userinput" function as well as a "menu" function that will be deployed each time the game prompts the user/player for input.
def menu():
print('Press "1" for map >>> "2" for stats >>> "3" for exit')
choice = input()
if choice == '1':
print('map needs to be made and shown')
elif choice == '2':
print('stats need to be made and assinged to choice 2 in def menu')
elif choice == '3':
print('You are exiting the menu. Press "M" at any time to return to the menu')
return
else:
print('I did not recognize your command')
menu()
def userinput():
print('Press 1 to attack an enemy >>> 2 to search a room >>> 3 to exit game')
print('Press "M" for menu at any time')
inputvalue = input()
if inputvalue == 'm':
menu()
elif inputvalue == '1':
print('attack function here')
elif inputvalue == '2':
print('search function here')
elif inputvalue == '3':
exit
else:
userinput()
This does not appear to be an ideal solution because the user cannot choose to view a map or exit the game at any time they want.
Is there a way to have a menu always running in the background?
I thought of using a while loop that would never close and all of the game would be held within that while loop but that doesn't seem economical by any means.
Any thoughts or help would be appreciated.
I took a stab at it. This is perhaps not the best structure for doing what you're looking for but I don't want my reply to get too complicated.
The "standard" approach for anything with a UI is to separate the model, the view and the control. Check out MVC architecture online. While it adds complexity at the start it makes life much simpler in the long run for anything with a non trivial UI.
Other points of note are:
you're not stripping whitespace from your input (potentially problematic "3 " won't do what you want)
you're input is case sensitive (you ask for "M" but check for "m") .. maybe use choice = choice.strip.lower()??
there's a difference between the way raw_input and input work between Python 2 and Python 3 which means your code doesn't work in python 2. What's the difference between raw_input() and input() in python3.x? I've changed my example to use raw_input. You may want to use this work around http://code.activestate.com/recipes/577836-raw_input-for-all-versions-of-python/ near the top of your code for portability.
Some code
# flag we set when we're done
finished = False
def finish():
# ask the user for confirmation?
global finished
finished = True
return
def handle_menu_input(choice):
handled = True
if choice == '1':
print('map needs to be made and shown')
elif choice == '2':
print('stats need to be made and assinged to choice 2 in def menu')
else:
handled = False
return handled
def menu():
finished_menu = False
while not finished_menu:
print('Press "1" for map >>> "2" for stats >>> "3" for exit')
choice = raw_input() # NOTE: changes behaviour in Python 3!
if handle_menu_input(choice):
# done
pass
elif choice == '3':
print('You are exiting the menu. Press "M" at any time to return to the menu')
finished_menu = True
else:
print('I did not recognize your command')
menu()
return
def userinput():
print('Press 1 to attack an enemy >>> 2 to search a room >>> 3 to exit game')
print('Press "M" for menu at any time')
choice = raw_input() # NOTE: changes behaviour in Python 3!
if choice == 'm':
menu()
elif choice == '1':
print('attack function here')
elif choice == '2':
print('search function here')
elif choice == '3':
finish()
# elif handle_menu_input(choice):
# # delegate menu functions?? ..
# # do this if you want to see maps anytime without going through the menu?
# # otherwise comment this elif block out.
# # (Problem is 1, 2 etc are overloaded)
# pass
else:
print('I did not recognize your command')
return
def main():
# main loop
while not finished:
userinput()
return
if __name__ == "__main__":
main()

Python 3.3: Can't get a function to return anything other than None

So, here's the relevant code:
def action():
print("These are the actions you have available:")
print("1 - Change rooms")
print("2 - Observe the room (OUT OF ORDER)")
print("3 - Check the room(OUT OF ORDER)")
print("4 - Quit the game")
choice = input("What do you do?\n> ")
if choice in (1, "move"):
return(1)
elif choice in (4, "quit"):
return(4)
play = True
while play == True:
###some functions that aren't relevant to the problem
choice = action()
print(choice)
if choice == 1:
change_room()
## more code...
The function always returns None. I put the print(choice) in there to see what value "choice" had and it always prinss none, and the "if choice == 1" block never runs. So I guess the function isn't returning a value at all, so the mistake is probably at the return()'s in action(), but I've checked here and elsewhere and I can't see what's wrong with it.
input() returns a string, always, but you are testing against integers. Make them strings:
if choice in ('1', "move"):
return 1
Your entered choice doesn't match any of your tests, so the function ends without ever reaching an explicit return statement and Python reverts to the default return value of None.
Better still, replace the whole if/elif/elif tree with a dictionary:
choices = {
'1': 1,
'move': 1,
# ...
'4': 4,
'quit': 4,
}
if choice in choices:
return choices[choice]
else:
print('No such choice!')

Categories

Resources