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
Related
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")
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.")
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
I am trying to create a simple while loop that will run the commands start, stop, quit, and help. Start, stop, and help will just display some printed text. After they are run, I want it to keep going on to another command. However, on quit I want the whole program to stop.
input_command = input("> ").lower()
while input_command != "quit":
print(input_command)
if input_command == "start":
print("The car is ready! VROOM VROOM!")
print(input_command)
elif input_command == "stop":
print("Car stopped.")
elif input_command == "help":
print("""
start - starts the car
stop - stops the car
quit - exits the program
""")
else:
print("Sorry, I don't understand that...")
You never reassign input command so it only ever takes input once,
input_command = ''
while input_command != "quit":
input_command = input("> ").lower()
I'm trying to make a Choose Your Own Adventure game in Python 3.X. I'm using the idle platform. Here is a sample of my code.
import time
again = True
while again == True:
print("You wake up as you normally do, but something's not quite right. What will be the first thing you do? \n Choices: \n Go back to sleep \n Get up")
action1 = input(": ")
if action1 == "Go back to sleep":
print("You lazyhead. As you were about to fall asleep, your ceiling collapsed on you and killed you. Don't be lazy.")
playAgain = input("Play again? Y/N: ")
if playAgain == "Y":
again = True
elif playAgain == "N":
again = False
Obviously, there is stuff between action1 and playAgain. I want to replace again = false in elif playAgain =="N"
elif playAgain =="N":
again = false
I want to instead jump to playAgain so I don't just end the program. This is my first question so my formatting is probably a bit weird so please correct that too.
As mentioned, python doesn't support GoTo. One way of achieving the same result is to create a quit game function like below then call it at the end of your main game code.
def quit_game():
playAgain = input("Play again? Y/N: ")
if playAgain == "Y":
return True
elif playAgain == "N":
quit_game()
In original code:
...
again = quit_game()