How to break out of double while loop in python? - python

Newbie python here. How can I break out of the second while loop if a user selects "Q" for "Quit?"
If I hit "m," it goes to the main menu and there I can quit hitting the "Q" key.
while loop == 1:
choice = main_menu()
if choice == "1":
os.system("clear")
while loop == 1:
choice = app_menu()
if choice == "1":
source = '%s/%s/external' % (app_help_path,app_version_10)
target = '%s/%s' % (target_app_help_path,app_version_10)
elif choice == "2":
source = '%s/%s/external' % (app_help_path,app_version_8)
target = '%s/%s' % (target_app_help_path,app_version_8)
elif choice.lower() == "m":
break
loop = 0
elif choice.lower() == "q":
break
loop = 0
sendfiles(source, target)
# Internal files
elif choice == "q":
loop = 0
App menu method:
def app_menu()
print "Select APP version"
print "-------------------"
print "1) 11"
print "2) 10"
print "3) 8"
print "m) Main Menu"
print "q) Quit"
print
return raw_input("Select an option: ")

You nearly have it; you just need to swap these two lines.
elif choice.lower() == "m":
break
loop = 0
elif choice.lower() == "m":
loop = 0
break
You break out of the nested loop before setting loop. :)

Change
break
loop = 0
to
loop = 0
break
in your elif blocks.

Use an exception.
class Quit( Exception ): pass
running= True
while running:
choice = main_menu()
if choice == "1":
os.system("clear")
try:
while True:
choice = app_menu()
if choice == "1":
elif choice == "2":
elif choice.lower() == "m":
break
# No statement after break is ever executed.
elif choice.lower() == "q":
raise Quit
sendfiles(source, target)
except Quit:
running= False
elif choice == "q":
running= False

Use two distinct variables for both loops, eg loop1 and loop2.
When you first press m in the inner loop you just break outside, and then you can handle q separately.
By the way you shouldn't need the inner variable to keep looping, just go with an infinite loop until key 'm' is pressed. Then you break out from inner loop while keeping first one.

Rename your top loop to something like mainloop, and set mainloop = 0 when q is received.
while mainloop == 1:
choice = main_menu()
if choice == "1":
os.system("clear")
while loop == 1:
choice = app_menu()
if choice == "1":
source = '%s/%s/external' % (app_help_path,app_version_10)
target = '%s/%s' % (target_app_help_path,app_version_10)
elif choice == "2":
source = '%s/%s/external' % (app_help_path,app_version_8)
target = '%s/%s' % (target_app_help_path,app_version_8)
elif choice.lower() == "m":
loop = 0
break
elif choice.lower() == "q":
mainloop = 0break
break
sendfiles(source, target)
# Internal files
elif choice == "q":
mainloop = 0

You could put this into a function and return:
import os.path
def do_whatever():
while True:
choice = main_menu()
if choice == "1":
os.system("clear")
while True:
choice = app_menu()
if choice in ("1", "2"):
app_version = app_version_10 if choice == "1" else app_version_8
source = os.path.join(app_help_path, app_version, "external")
target = os.path.join(target_app_help_path, app_version)
sendfiles(source, target)
elif choice.lower() == "m":
break
elif choice.lower() == "q":
return
Admittedly, I don't quite get when you want to break the inner loop and when you want to quit both loops, but this will give you the idea.

Related

Shopping cart Python

I've noticed that when I remove a item, I need to select the checkout option multiple times.
Anybody know why this is happening?
my_cart = []
def customerDecision(addItem, input1):
while True:
customerResponse = input("What would you like to do? add / remove / show / checkout / quit ")
if customerResponse.lower() == "add":
addItem = input('add what? ')
my_cart.append(addItem)
elif customerResponse.lower() == "show":
print(my_cart)
elif customerResponse.lower() == "remove":
input1 = input(f'remove what: {my_cart} ')
print(f'{input1} removed...')
elif input1 in my_cart:
my_cart.remove(input1)
elif customerResponse.lower() == "checkout":
for addItem in my_cart:
print(f"Thanks for purchasing {my_cart}: '\n'see you next time!")
break
elif customerResponse.lower() == "quit":
print("Thank you! We hope you find what you're looking for next time")
break
else:
print("Please try a valid command.")
customerDecision(addItem='', input1='')
Like this:
elif customerResponse.lower() == "remove":
input1 = input(f'remove what: {my_cart} ')
if input1 in my_cart:
my_cart.remove(input1)
print(f'{input1} removed...')
By the way, it would be more efficient if you said
customerResponse = customerResponse.lower()
once at the top, rather than calling that function 5 times.

How can I call functions via user input (with included parameters/values) using a similar method?

What I'm attempting to do is to take key words from user inputs and from there im attempting to call a function and parameter. For instance, if I were to remove a variable from a list, I would type remove -1 for the last value etc.
Code:
todo_list = [1, 3, 4, 5, 6]
def add_item(item):
item = 0
while len(todo_list) < maxLengthList:
item = input("Please enter your desired tasks: ")
todo_list.append(task)
print("Your to-do list so far: ")
def remove_item(idx):
del todo_list[idx]
return("This function removes! ")
def move_item(idx1, idx2):
return("This function moves! ")
def list_items():
for x in range(len(todo_list)):
return todo_list[x]
cmd_map = {'add': add_item, 'remove': remove_item, 'move': move_item, 'list': list_items}
while True:
cmd = input("Please input command: ")
if cmd.strip() == 'add':
add_item(item)
elif cmd.strip() == 'remove':
remove_item(idx)
exit()
elif cmd.strip() == 'move':
move_item(idx1 ,idx2)
exit()
elif cmd.strip() == 'list':
list_items()
exit()
elif cmd.strip() in cmd_map.keys():
cmd_map[cmd]()
else:
print("sorry no function for that!")
Try this
while True:
cmd = input("Please input command: ")
vars = cmd.split(' ')
if vars[0].strip() == 'add':
add_item(int(vars[1].strip()))
elif vars[0].strip() == 'remove':
remove_item(int(vars[1].strip()))
exit()
elif vars[0].strip() == 'move':
move_item(int(vars[1].strip()) ,int(vars[2].strip()))
exit()
elif vars[0].strip() == 'list':
list_items()
exit()
elif vars[0].strip() in cmd_map.keys():
cmd_map[cmd]()
else:
print("sorry no function for that!")
To eliminate any Extra spaces from user,
and to remove case sensitiveness
try:
import re
while True:
flag = 0
cmd = input("Please input command: ")
vars = re.split(r'\s+', cmd.strip())
if re.search('add', vars[0], flags=re.IGNORECASE):
flag = 1
add_item(int(vars[1]))
elif re.search('remove', vars[0], flags=re.IGNORECASE):
flag = 1
remove_item(int(vars[1]))
exit()
elif re.search('move', vars[0], flags=re.IGNORECASE):
flag = 1
move_item(int(vars[1]) ,int(vars[2]))
exit()
elif re.search('list', vars[0], flags=re.IGNORECASE):
flag = 1
list_items()
exit()
else:
for key in cmd_map.keys():
if re.search(key, vars[0], flags=re.IGNORECASE):
cmd_map[key]()
flag = 1
break
if flag == 0:
print("sorry no function for that!")
You can also use exec() to dynamically execute statements

B and C aren't working (Python3)

I'm quite confused at why the option "B" or "C" doesn't work. You are supposed to be able to navigate the story by choosing any of the 3 options. The only option that works is "A". It's probably the smallest thing I have overlooked.
Click to See the Code Window
The program executes (From the Fuctions.py, SplashScreens()):
...
print(SplashScreen.Splash_Screen19)
cls()
Story_1_to_4(Text.Story_1,2,3,4)
Which runs this... (Located in Functions.py){Through = True}{Key = False}
def Story_1_to_4(Story_Num, Path1, Path2, Path3):
global Through
global Key
if Path1 == 3 and Path2 == 4 and Path3 == 10:
Key = True
while Through == True:
Choice = input(Story_Num)
if Choice == "A":
Choice = Path1
Through = False
elif Choice == "B":
Choice = Path2
Through == False
elif Choice == "C":
Choice = Path3
Through == False
else:
cls()
print(Text.Invalid_Syntax)
time.sleep(2)
cls()
ResetThrough()
Decision(Choice)
Story_1: (From Text.py)
Image of the Variable Story_1
And then Decision is... (Located in Functions.py)
def Decision(Choice):
cls()
if Choice == 1:
Story_1_to_4(Text.Story_1,2,3,4)
elif Choice == 2:
Story_1_to_4(Text.Story_2,3,4,10)
elif Choice == 3:
Story_1_to_4(Text.Story_3,5,6,4)
elif Choice == 4:
Story_1_to_4(Text.Story_4,7,8,9)
elif Choice == 5:
Story_Ending(Text.Story_5)
elif Choice == 6:
Story_Ending(Text.Story_6)
elif Choice == 7 and Key == True:
Story_Ending(Text.Story_7_With_Key)
elif Choice == 7 and Key == False:
Story_Ending(Text.Story_7_Without_Key)
elif Choice == 8:
Story_Ending(Text.Story_8)
elif Choice == 9:
Story_Ending(Text.Story_9)
elif Choice == 10:
Story_Ending(Text.Story_10)
For A, you set Through = False. For B and C you wrote Through == False which just evaluates an expression but doesn't assign Through.

Is there a way convert an elif and a while statment into one ?

I'm am writing a simple program that look something like this:
while True:
choice = float(input("options: "))
if choice == 1:
# Do something
elif choice == 2:
# Do something
elif choice == 3: # <--- seems redudant
while choice == 3:
choice_return = input("do you want to return?: ")
if choice_return == "yes":
choice = None
else:
pass
elif choice == 4:
break
As noted in the the code, the "elif statment" seems redundant because it has the same conditions as the "while loop" below. You can of course simply write the code as follows:
while True:
choice = float(input("options: "))
if choice == 1:
# Do something
elif choice == 2:
# Do something
elif choice == 4:
break
while choice == 3: <--- three after four, no!!!
choice_return = input("do you want to return?: ")
if choice_return == "yes":
choice = None
else:
pass
which don't look to bad in this example, but in the actual code, it kinda ruins the structuring (and my OCD don't allow for that). Is there a way I can remove the redundancy while maintaining order?
NB. assume the "choice number" is fixed.
You can stick to the if/elif structure and clean up things by wrapping the logic of elif choice == 3 in a function and using a while True recipe in the function:
def myfunc()
while True:
choice_return = input("do you want to return?: ")
if choice_return == "yes":
return None # None here is redundant
while True:
choice = float(input("options: "))
if choice == 1:
...
elif choice == 3:
choice = myfunc()
...
There doesn't seem to be any reason to use choice as the condition in the while loop. Restructure it so it uses break to stop the loop when appropriate.
elif choice == 3: # <--- seems redudant
while True:
choice_return = input("do you want to return?: ")
if choice_return == "yes":
break
Put the inner while loop into a function, the code will then be much cleaner. You will still have both tests, but integer comparisons are fast - so why are you using float?
Better yet, if you could but every "case" into a function you could use a list of functions.
# Functions return True to break out of the loop, otherwise False
def case1():
# Do something
def case2():
# Do something
def case3():
# Do something
def case4():
# Do something
cases = [case1, case2, case3, case4]
while True:
choice = int(input("options: "))
if choice < len(cases) and choice >= 0:
if cases[choice]():
break
else:
print("Invalid option", choice)

Unexplained Invalid Syntax in Python 3.4.2

Whenever I press F5 to run my code, an error message pops up that reads 'invalid syntax', and the space after 'True' in the following line:
while not chosen4 == True
I have no idea what is causing this error.
The rest of the source code is below:
import time
playAgain = False
while not playAgain == True:
gameOver = False
print ("""Press ENTER to begin!
""")
input()
print("""text""")
time.sleep (2)
print ("""text""")
time.sleep (7)
print ("""text""")
print("""(Press a number and then ENTER!)""")
while not gameOver == True:
direction = input ("Your chosen action: ")
print("You chose {0}!".format(direction))
time.sleep (2)
if direction == "1":
print ("""text""")
time.sleep (6)
print ("""text""")
chosen1 = False
while not chosen1 == True:
direction1 = input ("Your chosen action: ")
print ("You chose {0}!".format(direction1))
time.sleep (2)
if direction1 == "3":
print ("""text""")
time.sleep (2)
print("""text""")
time.sleep (8)
print("""text""")
gameOver = True
break
elif direction1 == "4":
print("""text""")
time.sleep (3)
chosen4 = False
while not chosen4 == True
#The above line is where the 'invalid syntax' is.
direction4 = input ("Your chosen action: ")
print "You chose {0}!".format(chosen4)
time.sleep (2)
if chosen4 chosen4 == "7":
print ("text")
gameOver = True
break
elif chosen4 == "8":
print ("text")
gameOver = True
break
else:
tryagain
else:
print ("""text""")
time.sleep (3)
elif direction == "2":
print ("""text""")
time.sleep (2)
print("""text""")
time.sleep (3)
print("""text""")
chosen2 = False
while not chosen2 == True:
direction2 = input ("Your chosen action: ")
print ("You chose {0}!".format(direction2))
time.sleep (2)
if direction2 == "5":
print ("""text""")
time.sleep (8)
gameOver = True
break
elif direction2 == "6":
print ("""text""")
break
else:
print ("""text""")
elif direction == "0":
print ("""text""")
else:
print ("""text""")
if gameOver == True:
input()
You're missing the :
The body of the loop will need to be indented too
This indentation problem jumped out at me too
elif direction1 == "4":
print("""text""")
Missing colon on while not chosen4 == True, it should be while not chosen4 == True:.
You are missing indentation at elif direction1 == "4": on the print statement below.
Also this is not an error but instead of doing while not chosen2 == True: change it to while chosen == False: or while chosen != True: as it helps clean it up.

Categories

Resources