What commands are alternatives to "break"? [duplicate] - python

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 1 year ago.
Our teacher wants us to make a program that asks if you are ready and if YES or NO are typed then it should move on to the next question. For some reason he doesn't want us to use break and I can't find any command that really does anything similar to it other then continue, but continue only skips to the next line. Here is my code:
prompt = ""
while (prompt != "YES" or prompt != "NO"):
prompt = input ("Are you ready?(YES/NO): ")
if (prompt == "YES"):
print("Great!")
break
elif (prompt == "NO"):
print("How can I help?")
break
else:
print("Error, not a valid input")
while this would work in what I'm trying to achieve, I would get failed for having the break statement. Is there any alternative to this?

You might want to have a variable to that will check the condition such as valid_answer. Also, it is better practice to get rid of unnecessary parenthesis (if you expression is complex, they are fine, but in your case while loop condition is much simpler without them).
valid_answer = False
while not valid_answer:
prompt = input("Are you ready?(YES/NO): ")
if prompt == "YES":
print("Great!")
valid_answer = True
elif prompt == "NO":
print("How can I help?")
valid_answer = True
else:
print("Error, not a valid input")

You could just delete break from your code if you fixed your loop condition, changing:
while (prompt != "YES" or prompt != "NO"):
which is always true ("YES" is not equal to "NO", so the second test is true whenever the first one is false, so the loop condition is always true), with either:
while prompt != "YES" and prompt != "NO":
which is the minimal change to fix the logic (so it stops if it's equal to either value, rather than only when it's equal to both), or for a more English readability:
while prompt not in ("YES", "NO"):
which doesn't have the tricks of how != and and/or interact in boolean logic to worry about. Either way, after fixing the test, the code will work as written without the need for break at all.
To answer the broader question, the only alternatives to break are:
Careful use of tests to ensure the loop condition itself terminates when desired, and no code after the condition becomes true that should only execute when false is actually executed (this is what the minimal fix described above does)
Using return in a function (requires factoring the loop out of the function it is in)
Using an exception and try/except to jump out of the loop.
Not coincidentally, these are also your options when you need to break out of multiple levels of a nested loop (Python has no break that can break an arbitrary number of loops). #1 is frequently unpythonic (especially if it relies on flag variables; in your case, it's okay, just mildly redundant on the tests), as is #3, so if your code can't use break, and can't be restructured to avoid the need for it, #2 is usually the best solution, especially in complex cases.
Personally, I usually wouldn't put the handling of valid cases in the loop at all, leaving the loop to run and handle only invalid cases (which can occur 0-infinity times), with the valid cases handled after the loop is complete, exactly once.
A simple solution available on Python 3.8+ is to use the walrus operator (assignment expression for boring types) and just have the loop run until the result is valid, removing the handling for valid inputs from the loop entirely, putting them outside/after the loop entirely, so for your specific problem the end result would look like:
while (prompt := input("Are you ready?(YES/NO): ")) not in ("YES", "NO"):
print("Error, not a valid input")
if prompt == "YES":
print("Great!")
else: # No need for elif; only "YES" or "NO" would exit loop without throwing exception
print("How can I help?")
Pre-3.8, you could still do the same thing, the while is just a little uglier (more repeated code):
prompt = input("Are you ready?(YES/NO): ")
while prompt not in ("YES", "NO"):
print("Error, not a valid input")
prompt = input("Are you ready?(YES/NO): ")
Bonus, with no particular increase in code complexity, you drop from 9-11 lines of code in your current design (9 without break or explicit flag, 11 with) to 6-8 lines (6 with walrus, 8 without). With the walrus, it's strictly better; no code is repeated, no tests are repeated multiple times per loop, the loop is kept very simple.

Related

Having trouble with while loops, input and strings in python

I am learning python and practicing my skills my making a simple text based adventure game.
In the game, I want to ask the player if they are ready to begin. I did this by creating a begin() function:
def begin():
print(raw_input("Are you ready to begin? > "))
while raw_input() != "yes":
if raw_input() == "yes":
break
print(start_adventure())
else:
print("Are you ready to begin? > ")
print(begin())
below this in my code is the function start_adventure()
def start_adventure():
print("Test, Test, Test")
When I run the program it starts up and I get to the point where it asks if I am ready to begin. Then it just loops infinitely and I can only exit the program if I completely close Powershell and restart Powershell. What am I doing wrong? How can I get the loop to stop once the player inputs "yes"?
What do you expect this to do? The solution to your problem is to try to understand what the code does, instead of just throwing stuff together. (Don't worry; at least 80% of us were at that stage at one point!)
As an aside, I strongly recommend using Python 3 instead of Python 2; they made a new version of Python because Python 2 was full of really strange, confusing stuff like input causing security vulnerabilities and 10 / 4 equalling 2.
What do you want this to do?
Repeatedly ask the user whether they are ready to begin until they answer "yes".
Call start_adventure().
Ok. Let's put what we've got so far into a function:
def begin():
while something:
raw_input("Are you ready to begin? > ")
start_adventure()
There are a lot of gaps in here, but it's a start. Currently, we're getting the user's input and throwing it away, because we're not storing it anywhere. Let's fix that.
def begin():
while something:
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This is starting to take shape. We only want to keep looping while answer != "yes"...
def begin():
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
Hooray! Let's see if this works!
Traceback (most recent call last):
File "example", line 2, in <module>
while answer != "yes":
NameError: name 'answer' is not defined
Hmm... We haven't set a value for answer yet. In order to make the loop run, it has to be something that isn't equal to "yes". Let's go with "no":
def begin():
answer = "no"
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This will work!
Python 3 Solution
You should not be calling raw_input() multiple times. Simply instantiate x and then wait until the user inputs Y to call your start_adventure function. This should get you started:
def start_adventure():
print('We have started!')
#do something here
def begin():
x = None
while x!='Y':
x = input('Are you ready to begin (Y/N)?')
if x=='Y':
start_adventure()
begin()
Your Raw input function (I'm assuming it works correctly) is never assigned to a variable. Instead you call it in your print statement, print the result of it and then you call it again in your while loop condition.
You never actually satisfy the while loop condition because your input isn't assigned to a variable. Assign Raw_input("Are you ready to begin? >") to a variable to store the input. Then while loop with the variable. Make sure in your while loop when the condition is met you reset the variable to something else.
Your program flow is wrong too, you need to call your raw input function inside the while loop. This will change the while loop condition so that when the condition is met (user types "yes") it won't loop infinitely. Hope this helps!
Example of what you need in code form:
//initialize the condition to no value
condition = None;
#check the condition
while condition != "yes"
#change the condition here based on user input **inside the loop**
condition = raw_input("are you ready to begin? >")
if condition == "yes":
#condition is met do what you need
else:
#condition not met loop again
#nothing needs to go here to print the message again

How do I use an elif statement properly?

Please don't judge me.. I've only been working with Python for a month now.
While laying in my bed I thought of making this and created it in a few minutes but I made to many else and if statements and my code just looks so messy, I kept adding things that weren't needed..(For fun :D)
Anyways, here is my code.. If you could tell me how to use the "elif" statements properly that'd be awesome.(I'm still learning python)
Question: I've tried using an elif statement multiple times and I keep getting an error. How do I fix this?
key = True # Game key, if this is false the program won't work.
print("Please type a password: ") # Asking for users password
Pass = input()
print("Thank you for typing your password, please make sure it's secure by trying again..") # Ask them to confirm their password by re-typing it
Again = input()
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
else:
print("Something's wrong with your password or username!")
# Has user confirm if his information is correct
User = input()
print("checking..")
if User.isalpha() and key == True:
print("So your Username is " + User + " and your chosen password is: " + str(Pass))
else:
print("Either your key is broken or something is wrong..")
if len(User) >= 4: # Checking if the chosen username has 4 or more characters in it
print("The length of your Username is: ")
print(str(len(User)))
print("If this information is correct please type 'true' or 'false'")
else:
print("Please type a username longer than 4 characters!")
answer = input() # I kinda fucked up because my coding is dirty and unorganized lol..
if answer == str(True):
print("Thank you, we're setting up your account! :D")
else:
print("Please re-run the program and fix your information!")
We can't debug code you haven't posted, and (as is to be expected - you are on a learning exercise here, and there's a lot to think about) your program structure isn't very helpful. For example, when the user enters non-matching passwords you tell them about it, but nevertheless continue to ask them for their username. Don't worry about this, you will soon learn how to fix it.
Since you ask about the elif, it is basically a syntax abbreviation for else if that avoids going to multiple indentation levels. Suppose you wanted a value of '1' or '2' to take different actions, and to declare other values invalid. You could write
if value == '1':
#take action appropriate to 1
else:
if value == '2':
# take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Note that the different actions are at different indentation levels. The more cases you have to consider, the more levels of indentation you have to introduce. So it's generally felt to be more readable to write
if value == '1':
# Take action appropriate to 1
elif value == '2':
# Take action appropriate to 2
else:
raise ValueError("Allowed inputs are '1' or '2'")
Now all the actions and decisions are at the same indentation levels. That's pretty much all there is to it. If you leave the else case off then you won't take any actions at all, so it's normally used to specify the default action, in this case raising an exception.
PS: If you want to be sure the user has entered two matching passwords before you proceed, look at the while loop, which allows you to repeat a set of actions until some condition (in this case the passwords being equal) is true.
Here is an example if if/elif/else statement in python3:
test = 'mytest'
if test == 'not_my_test':
print('nope')
elif test == 'mytest':
print('yay')
else:
print('something else')
You can find more information here : https://docs.python.org/3/tutorial/controlflow.html
EDIT:
As a general remark, you should not define variable using capital letters (PEP convention: https://www.python.org/dev/peps/pep-0008/?)
So using Elif
if Pass == Again:
print("Thank you for choosing a working password, please create your character")
print("Please type your username without numbers")
elif Pass != Again:
print("Something's wrong with your password or username!")
Though what is this error you're getting, we can't really help you without it.

converting logic tests into try statements (python3)

I have been trying to convert some code into a try statement but I can't seem to get anything working.
Here is my code in pseudo code:
start
run function
check for user input ('Would you like to test another variable? (y/n) ')
if: yes ('y') restart from top
elif: no ('n') exit program (loop is at end of program)
else: return an error saying that the input is invalid.
And here is my code (which works) in python 3.4
run = True
while run == True:
spuriousCorrelate(directory)
cont = True
while cont == True:
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
cont = False
elif choice == 'n':
run = False
cont = False
else:
print('This is not a valid answer please try again.')
run = True
cont = True
Now what is the proper way for me to convert this into a try statement or to neaten my code somewhat?
This isn't a copy of the mentioned referenced post as I am trying to manage two nested statements rather than only get the correct answer.
If you want to make your code neater, you should consider having
while run:
instead of
while run == True:
and also remove the last two lines, because setting run and cont to True again isn't necessary (their value didn't change).
Furthermore, I think that a try - except block would be useful in the case of an integer input, for example:
num = input("Please enter an integer: ")
try:
num = int(num)
except ValueError:
print("Error,", num, "is not a number.")
In your case though I think it's better to stick with if - elif - else blocks.
Ok so as a general case I will try to avoid try...except blocks
Don't do this. Use the right tool for the job.
Use raise to signal that your code can't (or shouldn't) deal with the scenario.
Use try-except to process that signal.
Now what is the proper way for me to convert this into a try statement?
Don't convert.
You don't have anything that raises in your code, so there is no point of try-except.
What is the proper way to neaten my code somewhat?
Get rid of your flag variables (run, cont). You have break, use it!
This is prefered way of imlementing do-while, as Python docs says; unfortunately, I cannot find it to link it right now.
If someone finds it, feel free to edit my answer to include it.
def main()
while True: # while user wants to test variables
spuriousCorrelate(directory) # or whatever your program is doing
while True: # while not received valid answer
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
break # let's test next variable
elif choice == 'n':
return # no more testing, exit whole program
else:
print('This is not a valid answer please try again.')

User inputted script

I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")

While loop issues in Python

I'm trying to write a small Python program for use in secondary schools to teach about ciphers.
It's all part of an ongoing project they have to do.
However on my while loops I have an if condition inside them and if the condition isn't met the first time it just infinitely loops until I break.
while esc == False:
if guess != cipher:
print("ERROR: INCORRECT CIPHER:" + Decrypt(guess, enc))
pass
else:
esc = True
print("Correct Cipher! Decryption successful:" + Decrypt(guess, enc))
The cipher here is 12 and if that is input it carries on as normal, however any other input just gives the error message and loops out forever.
I'm from a C#/C++ background usually and I know Python needs to be in line with its tab characters and white space and I've checked that a few times but I'm at a loss now.
ADDITIONAL CODE:
This works fine and It's done the same way
while esc == False:
if CheckPassword(pw) == True:
print("Authorisation successful.")
esc = True
else:
pw = input("Password = : ")
ADDITIONAL PLACES WHERE SAME PROBLEM HAPPENS:
while esc == False:
if attempts < 1:
esc = True
GameOver()
elif x == "USERS":
print("USERS UNAVAILABLE.")
attempts = RemoveAttempt(attempts)
pass
I'm not sure what else you are expecting to happen. If the guess is incorrect once you get into the while loop, it is going to always be incorrect, because you never ask the user for another guess. Note that in the one that does work, the else clause has an input for a new password: you don't do that in either of your non-working examples.
(Also I think you might be confused about what pass does: it's simply a no-op, ie it does nothing at all, and is only useful where you syntactically need a statement but don't want to do anything. That's not the case in either of the places you use it, so you should remove it. Unless you perhaps meant break instead, to break out of the loop?)

Categories

Resources