I'm tired of trying to make a menu that let's me choose from a dictionary keys and in every value I have the choice. I found that I can use dictionary and get() method, it's working fine, but I should use if else statement after get() to execute a function that answers the user choice. Can I do it better? Maybe using a lambda inside the key value?
def menu():
print("Welcome to Our Website")
choises={
1:"Login" ,
2:"Register",
}
for i in choises.keys(): # Loop to print all Choises and key of choise !
print(f"{i} - {choises[i]}")
arg=int(input("Pleasse Chose : "))
R=choises.get(arg,-1)
while R==-1:
print("\n Wrong Choise ! Try again ....\n")
menu()
else:
print(f"You Chosed {R}")
if R==1:
login()
if R==2:
register()
def register():
print("Registration Section")
def login():
print("Login Section")
menu()
you can simulate a switch statement using the following function definition:
def switch(v): yield lambda *c: v in c
You can use it in C-style:
x = 3
for case in switch(x):
if case(1):
# do something
break
if case(2,4):
# do some other thing
break
if case(3):
# do something else
break
else:
# deal with other values of x
Or you can use if/elif/else patterns without the breaks:
x = 3
for case in switch(x):
if case(1):
# do something
elif case(2,4):
# do some other thing
elif case(3):
# do something else
else:
# deal with other values of x
It can be particularly expressive for function dispatch
functionKey = 'f2'
for case in switch(functionKey):
if case('f1'): return findPerson()
if case('f2'): return editAccount()
if case('f3'): return saveChanges()
Related
I'm still super beginner in learning python right now and english is not my native language .I hope there is someone can answer my problem. My concern is how can I end all the loop when enter 'e'. I try to modify the code so that it exit all the loop when enter 'e' but the when I also enter 'm' , it also same when enter 'e' instead I want to return back to the menu loop when I enter 'm'. Thank you. Code below
def A():
print("a")
def B():
print("B")
def Menu():
print("Menu")
print("1.A")
print("2.B")
while True:
Menu()
while True:
option = input("Choose a or b")
if option == 'a':
A()
break
elif option == 'b':
B()
break
else:
print("Choose 'a' or 'b' only")
while True:
repeat = input("'m' or 'e'")
if repeat != 'e' and repeat != 'm':
print("Choose 'm' or 'e' only'")
if repeat == 'm':
break
if repeat == 'e':
break
break
I undestand your problem so I'll give you the only clean solution:
while True: # A loop
while True: # B loop
...
# Now from here...
# ...you want to go here?
If you want to exit both B and A loop from inside B loop, there's only one clean way:
def foo():
while True:
while True:
...
return # Will end both loops
Put the whole thing into a function and replace the "double break" with return.
There's an other solution that I would nickname "boolean label solution" which works in most cases but it's less clean so I will just give you a clue.
flag = true
while flag:
while True:
if (condition_to_exit):
flag = false
break
If you just wish to exit the program after exiting the loops, just use the exit() function:
while True:
...
while True:
...
exit()
I'd recommend creating functions for the user input, this way your code will be cleaner and easier to understand.
Look how clean the main loop looks now, it's very clear what it does:
Executes the Menu function
Lets the user choose whether to execute A or B
Asks user to input "m" or "e"
If user inputs "e" it breaks the loop
That's the steps the main loop has to do, so that's all the code that should be there. Code for checking if the user inputs the right options is not the main loop business, it should be inside a function.
This way you delegate tasks and responsibilities to different parts of the code, which for bigger projects it might not be you who programs them.
The code than be further improved and refactored, for example you might want to use dictionaries for the options of your menu. So each key is an option and the value is the function to be executed. This way your Menu() would be just a loop iterating over the dictionary to display the options and then executing the associated function.
Also you might want to take a look at classes, since all this will fit better encapsulated inside a class.
But first and most important: Keep your code clean, self descriptive and organized.
def A():
print("a")
def B():
print("B")
def Menu():
print("Menu")
print("1.A")
print("2.B")
def ExecuteAorB():
while True:
option = input("Choose a or b")
if option == 'a':
A()
break
elif option == 'b':
B()
break
else:
print("Choose 'a' or 'b' only")
def AskUserMorE():
while True:
repeat = input("'m' or 'e'")
if repeat not in ('e', 'm'):
print("Choose 'm' or 'e' only'")
else:
return repeat
while True:
Menu()
ExecuteAorB()
userInput = AskUserMorE()
if userInput == 'e':
break
This question already has answers here:
Recursive function does not return specified value
(2 answers)
Closed 8 months ago.
Apologies for the confusing title, but here is a very simplified version of what I mean:
def main():
burger = 0
shake = 0
run = True
while run:
choice = show_menu()
if choice == "burger":
qt_burger += 1
elif choice == "shake":
qt_shake += 1
else:
show_bill
def show_menu():
choice = input("Burger or Shake?: ")
if choice not in ["burger", "shake"]:
show_error(choice)
else:
return choice
def show_error(choice):
print(f"{choice} is not an option")
show_menu()
main()
Function 'main' defines variable 'choice' based on what is returned from function 'show_menu'. If show_menu does not call show_error, the program properly returns the input value back to 'choice' in 'main'. However, if show_error is called, show_menu is called again, and a proper value is entered the second time, choice in main becomes 'none'. Is there any way around this while keeping all these separate functions? I have also tried re-calling show_menu from within itself rather than from within the error function, but it is the same result.
Incase of choice is invalid, you are calling show_error, after executing this function(show_error) the interpreter will just move to next line i.e the end of show_menu function which implicitly return None
.But if you return show_error(), the interpreter will execute this function and return whatever value show_error will return.
def show_menu():
choice = input("Burger or Shake?: ")
if choice not in ["burger", "shake"]:
return show_error(choice)
else:
return choice
def show_error(choice):
print(f"{choice} is not an option")
return show_menu()
A simpler(more readable) way can be
def read_input():
return input("Burger or Shake?: ")
def show_menu():
choice = read_input()
while choice not in ["burger", "shake"]:
show_error(choice)
choice = read_input()
return choice
def show_error(choice):
print(f"{choice} is not an option")
i am building scientific calculator. After performing the operation it ask do u want to go back in main menu or Exit
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
continue
else:
break
when user press y it go back to main menu otherwise exit
You can`t use break and continue in function, read tutorial
instead, you can use check in your main loop, and your function must return True or False
def Again():
x=input ("Go back to main menu(Y/N)")
if (x=='Y') or (x=='y'):
return True
else:
return False
while True: # your main loop
# some other code
# check on exit
if Again():
continue
else:
break
This can work!
class Cal:
def main_menu(self):
print ("I am in main menu")
def again(self):
x = raw_input("Go back to main menu(Y/N)")
if x == 'y':
self.main_menu()
if __name__ == '__main__':
c = Cal()
c.again()
When you will enter y it will go to the main menu.
Also, continue and break will not work here as they both are applied in loops.
You can use raw_input instead of input as input does not accept string values.
A beginner's problem, here it goes:
I'm writing a program which keeps records of a game of darts. The user types in the players and their respective scores. It's possible to do a query about a player's scores and ask the program for the best overall score between all the players. I have the following functions:
add_score
return_players_score
return_best_score
exit_program
main
In main(), we begin by creating a new empty dictionary (say, players = {}). Then we ask the user to input a number that takes him/her to the function of choice (1: add_score etc.).
Now, once we're in add_score and have added a key:value pair (player:score), we need to go back to inputting the number taking to the function of choice. I implemented it simply by writing main() to the end of add_score.
That, however, takes us to the beginning, where there's players = {} and thus whatever data we input in add_score gets wiped out. This then affects other functions and the program remains useless as long as it forgets everything right away. How to solve this?
I'd paste the actual code but it's not in English and it's an assignment anyway...
Thanks.
Rather than calling main() from each of your other functions, you should just return (or run off the end of the function, which is equivalent to return None). Since you need the main function to run things repeatedly, you should use a loop.
def main():
players = {}
while True: # loop forever (until a break)
choice = input("what do you want to do (1-4)")
if choice == "1":
add_score(players)
elif choice == "2":
return_players_score(players)
#...
elif choice == "4":
break # break out of the loop to quit
else:
print("I didn't understand that.")
If you have a loop that does something like the following..
example:
while True:
players = {}
some code adding to players
This loop will always reset players to {}
However, if you do:
players = {}
while something:
some code adding to players
then players is not being reset at the start of each iteration through the loop
But your question is not clear
If you have something like this:
def add_score(dicccionary):
#do something with diccionary
main()
def main():
dicccionary = {}
while something:
option = input("option")
if option == 1:
addscore(dicccionary)
else:
#otherfunction
main()
your reset problem can be solve like:
dicccionary = {} #global variable
def add_score():
#do something with diccionary
main()
def main():
option = input("option")
if option == 1:
addscore()
else:
#otherfunction
main()
By the way, you shouldn't make it this way, try something as:
dicccionary = {} #global variable
def add_score():
#do something with diccionary
def main():
while somecondition:
option = input("option")
if option == 1:
addscore()
else:
#otherfunction
main()
If I was doing it for real then I would go for something like:
import sys
class ScoreKeeper(object):
def init(self):
self.scores = {}
def add_score(self, player, score):
self.scores[player] = score
def _print_player_score(self, player, score):
print 'player:', player, 'score:', score
def print_scores(self):
for player, score in self.scores.items():
self._print_player_score(player, score)
def best_score(self):
best, player = 0, "no player"
for player, score in self.scores.items():
if score > best:
best, player = score, player
self._print_player_score(player, best)
if __name__ == '__main__':
scorer = ScoreKeeper()
quit = lambda: sys.exit()
choices = quit, scorer.add_score, scorer.print_scores, scorer.best_score
def help():
print 'Enter choice:'
for index, c in enumerate(choices):
print '%d) %s' % (index, c.__name__)
def get_integer(prompt):
res = raw_input(prompt)
try:
return int(res)
except:
print 'an integer is required'
return get_integer(prompt)
def get_choice():
choice = get_integer('choice? ')
if not 0 <= choice < len(choices):
help()
return get_input()
return choice
help()
choice = get_choice()
while(choice):
args = []
if choices[choice] == scorer.add_score:
args.append(raw_input('player name? '))
args.append(get_integer('score? '))
choices[choice](*args)
choice = get_choice()
quit()
I am trying to make an on/off switch for my program:
(see after the ### for what I'm talking about)
while 1:
str = raw_input("insert your word: ")
n = input("insert your scalar: ")
def string_times(str, n):
return n * str
print string_times(str, n)
###
def switch(on,off):
raw_input("On or off? ")
if switch == "on":
continue
if switch == "off":
break
switch(on,off)
I get a continue not in loop error. Basically, I want to create an on or off switch after the program runs once. What do I fix?
You cannot use break and continue in a nested function. Use the return value of the function instead:
def switch():
resp = raw_input("On or off? ")
return resp == "on":
while True:
# other code
if not switch():
break
Note that there is little point in defining your functions in the loop. Define them before the loop, as creating the function object takes some performance (albeit a small amount).
The switch() function needs no arguments (you didn't use them at all), and the continue is also not needed. If you didn't break out of the loop, it'll just continue from the top when you reach the end.
You only need continue if you want the loop to start at the top again skipping the rest of the code in the loop:
count = 0
while True:
count += 1
print count
if loop % 2 == 0:
continue
print 'We did not continue and came here instead.'
if count >= 3:
break
print 'We did not break out of the loop.'