Is there a use of break statement in python? I noticed that we can end the while loop with another faster ways.
As an example we can say:
name=""
while name!="Mahmoud":
print('Please type your name.')
name = input()
print('Thank you!')
instead of:
while True:
print('Please type your name.')
name = input()
if name == 'Mahmoud':
break
print('Thank you!')
and what is the meaning of while True?
break is useful if you want to end the loop part-way through.
while True:
print('Please type your name.')
name = input()
if name == 'Mahmoud':
break
print('Please try again')
print('Thank you!')
If you do this with while name != 'Mahmoud':, it will print Please try again at the end, even though you typed Mahmoud.
while True: means to loop forever (or until something inside the loop breaks you out), since the looping condition can never become false.
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 a code sample where the problem is:
while True:
for i in range(3):
i = input()
if i == 'quit'
break
else:
print('Try again')
When I type quit in my input it doesn't break out of the code. Thanks for your help!
Try using this code:
while True:
i = input()
if i == 'quit'
break
print('Try again')
I removed for loop because it has no usage and for loop is the reason of break not working because you are breaking out of for loop and not the while loop. I also removed else in if statement.
You're just breaking out of the for loop, not the while loop. If you want to get out of while loop then use this code:
while True:
for i in range(3):
i = input()
if i == 'quit':
break
else:
print('Try again')
continue
break
As Vishwa Mittar explained your code "break" works only for inner loop not for outer loop So you can use flag for while loop instead of bool as below
flag = True
while flag:
for i in range(3):
i = input()
if i == 'quit':
flag=False
break
else:
print('Try again')```
NOTE - The following answer(s) assume(s) that you need the for loop for some purpose.
The break statement is breaking out of the for loop. You need to create a variable outside the for loop with its value set to false. In the if i == 'quit', you need to set that variable to true. Then outside the for loop you need to check if that variable is true. If so, break out of the while loop.
So the final code would look something like this :-
while True:
exit_loop = false
for i in range(3):
i = input()
if i == 'quit':
exit_loop = true
break
else:
print('Try again')
if exit_loop: break
EDIT:
Another solution could be to raise an error and handle it using the try statement.
while True:
try:
for i in range(3):
i = input()
if i == 'quit':
raise ValueError('')
else:
print('Try again')
except Exception as e:
break
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.")
Pardon my cheap question, I am still a beginner!
Task: In the block of code below, I want the user to be able to try 3 wrong names,
and the program should possible print ‘you have reached the maximum attempts’
before the ‘Break’ command will execute. How can I achive this?
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
name = input()
#[I need to add some iterations here!]
break
print('Thank you!')
Try this:
tries=1
while True:
name = input('Please type your name\n')
if name != 'Louis':
if tries!=3: #==== If tries is not equal to 3
print('Name is incorrect check and enter your name again!')
tries+=1 #=== Add 1 to tries
else:
print("You have reached maximum attempts.")
break #=== Break out of loop
else:
print('Thank you!')
break #=== Break out of loop
Here, this should help. You just iterate over the number of attempts you want to give the user (here it is 3 attempts). You could also use the while True loop with a counter.
nbr_of_tries = 3
for i in range(nbr_of_tries):
print('Please type your name')
name = input()
if name == 'Louis':
print('Thank you!')
#[I need to add some iterations here!]
break
elif i < nbr_of_tries-1:
print('Name is incorrect check and enter your name again!')
else:
print('Maximum number of tries reached. Exiting')
you can do something like this:
x=0
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
name = input()
#[I need to add some iterations here!]
if x==3:
print("you have reached the limit")
break
else:
x=x+1
else:
print('Thank you!')
break
count = 0
while True:
print('Please type your name')
name = input()
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
count += 1
#[I need to add some iterations here!]
if count > 2:
break
else:
print ("Required name entered")
break
print('Thank you!')
You can do this without break, something like this.
attempt = 0
while True and attempt < 3:
attempt += 1
print('Please type your name')
name = input()
if name != 'Louis':
if attempt == 3:
print('you have reached the maximum attempts')
else:
print('Name is incorrect. Please check and try again!')
print('Thank you!')
like this?
while True:
print('Please type your name')
name = input()
attempts = 3
while attemps:
if name != 'Louis':
print('Name is incorrect check and enter your name again!')
attempts -= 1
name = input()
else:
print('maximum attempts reached')
print('Thank you!')
Explanation:
During the while loop the attempts-counter will be decremented if the if statement is True and the user can enter another name. If the counter reaches 0, the loop will stop and the maximum attempts reached message will be printed.
I wrote a while loop asking the user whether they're male or female. Everything after "else" has been greyed out. When I hover over it with my mouse it says:
"Code is unreachable Pylance".
sex = input('What is your sex? (m/f/prefer not to say) ')
while True:
sex = input('What is your sex? (m/f/prefer not to say' )
print('success:)')
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")
How can this be fixed?
Note the differences. the break exit the loop totally.
The while loop continues operation as long as it condition evaluates as True. so therefore you need to create condition to either break from the loop within your code or modify the loop to evaluate as false.
Also, you would realise that when the loop eventually turns false only then is the else statement called. However, the else wont be called if break keyword was used to exit the loop.
tries = 5
opt =('m','f','prefer not to say')
while tries: #evaluates True but false if tries = 0
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
tries -=1
continue
print('success:)')
tries=0 # note here the bool(0) == False
else:
print('happens if there is no break from the loop')
print("we're out of the loop")
#opt 2
while True:
sex = input('What is your sex? (m/f/prefer not to say' ).lower()
if sex not in opt:
print("sorry doll, I can't help you:( let's try again.")
continue
print('success:)')
break. # completely exits the loop
else:
print("sorry doll, I can't help you:( let's try again.")
print("we're out of the loop")