Control flow - Jump to another loop? - python

I did not find any duplicates of this question, i understand that Python has no "goto" functionality in itself and how i can make use of "continue" in a loop to get the same effect, but i'm not really sure if it's any recommended method of "jumping back" to another loop for eg? Let me show you an example below
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
pass
# Here i would want to be able to send the user back to the 1st loop if user gives any other input than "yes" or "no"
The only thing i can think of right now that makes any sense (to not have to simply rewrite the whole thing again) is to simply set the first loop to a function and call that from the second loop to get the result i want, this works as i intend it to:
def firstloop():
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
firstloop()
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
firstloop()
But somehow it feels like i'm over complicating something, or is this the "best" way i can go by with something like this? Thanks

You should put the second loop inside the first one (or inside an enclosing while for both). GOTOs are never needed, See here: https://en.wikipedia.org/wiki/Structured_programming

Related

How to make a while loop continue to loop if certain parameters aren't met?

still a beginner at programming, so forgive the mistakes:
I am trying to make my user-defined function loop until the user types in "no."
However, when I was adding extra functions to foolproof the loop, i.e. check to make sure what they typed was actually "yes" or "no" and not random garbage/numbers, it seems to run into problems. Here is the loop statement:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop != "no" or "yes":
print("INVALID INPUT")
elif stop == "no":
break
else:
continue
First "if" is checking whether the input was not "no" or "yes", next "elif" is checking if the input was "no" and if so stop the program, and "else" (yes) continue. Instead, it asks if I would like to continue, tells me "INVALID INPUT" no matter what, and continues. What am I doing wrong?
stop != "no" or "yes" is not the correct syntax. What you want is either not (stop=="no" or stop=="yes") or stop not in ["no","yes"].
Consider the following modified version of your code:
while True:
percentConvert()
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop) #added for debugging
if stop not in ["no","yes"]:
print("INVALID INPUT")
elif stop == "no":
break
Note that the above, while it technically runs, will run percentConvert() in response to an invalid input. Here's a script that behaves in what I suspect is the desired way.
while True:
percentConvert()
while True:
stop = input("Would you like to continue? yes or no: ".lower())
print("You inputted:", stop)
if stop not in ["no","yes"]:
print("INVALID INPUT")
else:
break
if stop == "no":
break
In the loop as it's currently written, the condition is being interpreted as (stop != "no") or ("yes"). "yes" is a non-empty string, which Python considers to be a "truthy" value, which means that the or and if treat "yes" as if it were True, which means that the if-block always executes.
This is a good use case for using custom error handling.
First define the base class for errors, and a custom exception.
# define Python user-defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class InvalidInputError(Error):
"""Rasied when user input is not yes/no"""
pass
Then in your while loop, you can use the exception.
percentConvert()
while True:
try:
stop = input("Would you like to continue? yes or no: ".lower())
if stop == 'yes':
percentConvert()
continue
elif stop == 'no':
break
else:
raise InvalidInputError
except InvalidInputError:
print("Must enter either yes/no")

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

Why will the While Loop not end when I ender the correct input?

I have had an issue where I can't get the While loop to terminate.
userinput = ("")
while userinput != ("Search" or "Add"):
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else: print("please choose from the following two options.")
Edit: I am sorry the changes have worked. I think after I implemented the changes I had an issue with the Shell running the previous version. Sometimes I have no idea what is happening. Thank you all again.
Edit Edit: Placed the original code back in as I did not take into account that it would confuse anyone looking for their own solution. I am quite new in terms of usage of the site. Thanks again for the help
The issue is with your while test. A couple of things:
You can't use or like this. or needs two full conditions that resolve to true or false. Here you have one condition userinput != "Search" and a string "Add". So it's always going to return True since a non-zero value is always True.
As an example:
if "Add": print("true")
>>true
Instead:
userinput != "Search" or userinput != "Add"
or is not correct when testing two negations like !=. One of the two conditions will always return true. For instance if you input "Add" then the condition userinput != "Search" will be True and your while loop will continue since True or False = True. So on and so forth. Instead you want an and.
while userinput != "Search" and userinput != "Add":
As I suggested in my comment though, it's probably just easier to use the not in operator on a list:
while userinput not in ['Search','Add']:
This way as your list grows your test stays nice and small/condense.
Also, while this is just my opinion, I applaud your original pre-edit code where you supplied the condition for breaking your while loop in the while statement instead of doing while True:. Having had many years of bug hunting and feature adding and hotfixing, I know every time I see while True: I'm going to be hunting through hundreds of lines of codes looking for every break. while True: and break has its time and place (I imagine), but I feel like it should be an exception use-case, not the rule.
My solution looks like this:
userinput = ""
while userinput != "Exit":
userinput = input("Search, Add or Exit: ")
if userinput == "Search":
print("run search request")
elif userinput == "Add":
print("run add request")
elif userinput != "Exit":
print("please choose from Search, Add or Exit.")
Notes:
Variable userinput is initialised to "". It doesn't need to be a tuple, ("")
I introduced an 'Exit' option. We loop until we encounter Exit. No need for break or continue
I changed the prompt to a colon and a space, and also show the three options.
We compare the input to the three options. If nothing valid, print an error message
As an alternative, you can use the following, using continue in the else clause, and break at the end of the while block. This way, it is easier to add more elif clauses, without potentially forgetting a break statement.
(It also doesn't require setting a default value for userinput, since that is done as the first thing in the while loop.)
while True:
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else:
print("please choose from the following two options.")
continue
break
Using the word break will break you out of a while loop, like this:
while True:
break
Place break where you want the while loop to end.
The problem is that once the input is received, and when the input meets the end condition of the while loop, and it isn't able to reach the code checking for the condition! Try this:
while True:
userinput = input("Search or Add?")
if userinput == "Search":
Search()
break
elif userinput == "Add":
print("run add request")
break
else: print("please choose from the following two options.")
The format was not correct in the while condition statement part, You can try out this...
userinput = ("")
while userinput not in ["Search", "Add"]:
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else: print("please choose from the following two options.")

Conditional infinite python loop

Im quite new to python and am struggling with an infinite loop. It seems that this should work given the user input is no however it just kills the program.
start = "no"
while start.lower() == "no":
start = input("Are you finished?")
break
break unconditionally aborts the while loop. Remove it, like this:
start = "no"
while start.lower() == "no":
start = input("Are you finished?")
Alternatively, if you want to use break, make it conditional:
while True:
start = input("Are you finished?")
if start.lower() != "no":
break

Why isn't this code repeating? Python 3.3

This is a code that I have used when repeating a sequence I have used but it doesnt seem to be working can anyone see any problems?The code is for a currency converter. Im using Python 3.3
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Edit,This is the rest of the code:
if userChoice == "1":
userUSD = float(input("Enter the amount of USD you wish to convert.\n"))
UK = userUSD * 0.62
print("USD", userUSD, "= ", UK, "UK")
elif userChoice == "2":
UK = float(input("Enter the amount of UK Currency you wish to convert.\n"))
userUSD = UK * 1.62
print("UK", UK, "= ", userUSD, "USD")
def doagain():
userDoAgain = raw_input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Generally speaking, using recursion to handle a repeated control flow in Python is a bad idea. It's much easier, and less problematic to use loops instead. So, rather than defining a function doagain to ensure you get an answer to your question about running again, I suggest using a while loop. For the larger function that you'll be repeating, I suggest using a loop as well.
def repeat_stuff():
while True: # keep looping until told otherwise
# do the actual stuff you want to do here, e.g. converting currencies
do_stuff_once()
while True: # ask about doing it again until we understand the answer
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain.lower() == "yes":
break # go back to the outer loop
elif userDoAgain.lower() == "no":
print("Thank you for using this program")
return # exit the function
else:
print("Error: You entered invalid information.")
Note that I've changed the checks of the yes/no input strings to be case insenstive, which is a rather more user friendly way to go.
You are using recursion (the function calls itself) while it may be much nicer to just wrap the code you want to repeat in a while loop.
Example of this usage:
userContinue = "yes"
while (userContinue == "yes"):
userInput = input("Type something: ")
print("You typed in", userInput)
userContinue = input("Type in something else? (yes/no): ").lower()
Probably you need to use the function "raw_input" instead of only input.

Categories