How to break the while loop if the condition is False? - python

I have a long function in which I am checking for different parameters and if any of the parameters is False, I don't want to execute the code further.
For your understanding, this is how I want to make it work
Email = True
while(Email == True):
print("Execute Me")
Email = False # Break the while loop here
print("Never execute me")
Here is the pseudo version of my code:
def users_preferences(prefs):
for pref in prefs:
send_email = True
while(send_email == True):
# Set send_email = False if email is not verified and don't move to the next line
# Set send_email = False if user's email is not a part of specific group
...
...
How can I break the loop if the condition is False at any point without further executing the code?
Edit: The problem with break statements is that it will become cumbersome to check the condition before running a new statement where you have number of statements

You can use a normal break statement:
Email = True
while Email:
print("Execute Me")
Email = False # Break the while loop here
if not Email:
break
print("Never execute me")
Edit: If the while loop doesn't do anything special, the code can be modified to be:
for pref in prefs:
if not is_email_verified(email) or not is_user_in_group(user, group):
continue
send_email(email)

Hello your code needs to be better indented. Also why haven't you tried using break statement to get out of the loop?
Email = True
while Email:
# do something
break
# continue doing something

Related

Seeking assistacne with an on online Python course exercise please

I have been doing an online Python course and the final exercise was to check a list of email addresses for invalid addresses.
The code is
def has_invalid_characters(string):
valid = "abcdefghijklmnopqrstuvwxyz0123456789."
# your code here
for i in string:
if i not in valid:
return True
else:
return False
def is_valid(email):
if email.count("#") != 1:
return False
prefix, domain = email.split("#")
if len(prefix) == 0:
return False
if domain.count(".") != 1:
return False
domain_name, extension = domain.split(".")
if len(domain_name) == 0 or len(extension) == 0:
return False
if has_invalid_characters(prefix) == True:
return False
if has_invalid_characters(domain) == True:
return False
else:
return True
emails = [
"test#example.com",
"valid#gmail.com",
"invalid#gmail",
"invalid",
"not an email",
"invalid#email",
"!#/",
"test##example.com",
"test#.com",
"test#site.",
"#example.com",
"an.example#test",
"te#st#example.com",
"test#exam!ple.com"
]
for i in emails:
is_valid(i)
if i == True:
print(i + " is valid")
else:
print(i + " is invalid")
When I run this I am told that the first two email addresses, which should be reported as valid, are invalid, but I cannot figure out why. I have gone over it a few times and cannot see an error in the logic. I have also run it on my laptop and I get the same result.
In the course this code was written in steps and with the last step to change the for loop from simply printing the email addresses to validating them and everything until I modified the for was marked as correct.
I would be grateful if someone could point out the issue with this code to me.
I found the issue. My call to the is_valid() function was not correct.
it should be
for i in emails:
result = is_valid(i)
if result == True:
.....
Sorry for troubling you with this.

invalid email and return to begining

I'm new to python I got a question that might be easy but i can't get it.
i wanted to make aprogram that user gives email as username and password as password ,the program should check if email is in corect format and if its not it should print something and get email again so i used regex (Im giving this inputs to database and i thought using LIKE query but i don't think that might help)
so whats the problem with my code?!it keeps wrong email
import re
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
def check(email):
if (re.fullmatch(regex, email)):
return
else:
print("corect format is like amireza#gmail.com")
return
while __name__ == '__main__':
username = input()
check(username)
password = input()
here is a working code for you:
import re
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
def check(email):
if (re.fullmatch(regex, email)):
return True
else:
print("invalid input! correct format is like amireza#gmail.com")
return False
while __name__ == '__main__':
while True:
username = input("please enter email\n")
if check(username) is True:
break
password = input("please enter password\n")
break
print("username: %s, password: %s" % (username, password))
key correction:
your helper should return a boolean which lets you know if the input is legit or not. thus I returned a boolean to outside scope
one more thing: since you run it as a standalone script, the outermost while condition (while __name__ == '__main__') will always be True, which means you have to break out of it when you want to end your program execution. For simplicity I'd suggest using if __name__ == '__main__' instead
You could change your function check to return a boolean output that tells you whether the check was successful, as in
def check(email):
if (re.fullmatch(regex, email)):
return True
else:
print("corect format is like amireza#gmail.com")
return False
And then add a loop to your main code:
if __name__ == '__main__':
username = input()
while not check(username):
username = input()
Note that I did not actually run your code, but this should work.
EDIT: Heh, right, as the other answer explains, you should change your while into an if, I edited my code correspondingly.

Get user input to stop a while loop

I need a way to stop a loop by getting user input without blocking the loop itself which works cross-platform.
Things I have tried:
processes (closes stdin so I can't use input())
threads (can't kill a thread if the while loop terminates and I no longer need the input())
FLAG = False
def break_main_loop(): # how do I get this to execute?
global FLAG
user_in = input()
if user_in == 'stop':
FLAG = True
return
else:
break_main_loop()
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if FLAG:
break
return # if I return here, I need to cancel break_main_loop's input()
main()
This will work for you and simple to use. Replace main function with this
def main():
# do stuff, e.g. getting other user input()
try:
while True:
stuff()
except KeyboardInterrupt:
print("Press 1 to quit")
return # if I return here, I need to cancel break_main_loop's input()
main()
I'd love to answer your question. You see, once you are in the main-loop, you don't necessarily need to use a FLAG variable, rather, I'd suggest doing something like this :
def break_main_loop(): # how do I get this to execute?
user_in = input()
if user_in == 'stop':
return True # Returning integer 1 also works just fine
else:
return False # Returning integer 0 also works just fine
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if break_main_loop(): # If the user inputs stop, the loop stops via the return statement automatically
return
main()
If you wish to get out of the loop without returning anything else and keep the main() function running for doing stuff:
def break_main_loop(): # how do I get this to execute?
user_in = input()
if user_in == 'stop':
return True # Returning integer 1 also works just fine
else:
return False # Returning integer 0 also works just fine
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if break_main_loop():
break
#continue doing stuff
main()
Now, there's a better way to break out of the loop without using the helper function break_main_loop(), and that's done like so:
def stuff():
pass
def main():
# do stuff, e.g. getting other user input()
while True:
stuff()
if str(input("Do you wish to continue:[y/n]")) == 'n':
break
#continue doing stuff
main()
This lets you get rid of the helper function completely.
I hope this answer was helpful. :D
try this:
class new_game:
start_game = True
# end_game = False
def break_main_loop(self): # how do I get this to execute?
print("game is ending!")
def stuff(self):
print("this is stuff happening....now...game is: ", self.start_game)
def game_loop(self):
user_in = int(input("enter '2' to end game or '1' to keep playing:" ))
if user_in == 1:
self.stuff()
self.game_loop()
else:
return self.break_main_loop()
Test_game = new_game()
Test_game.game_loop()

Possible ways to change flag values inside a while loop in python?

So my problem is this: I'm running a while loop that will execute Function1 every time, Function2 and Function3 will only be executed when their respective flags are set to True, and I want to be able to alter those flags while the loop is running.
while brkFlag == False:
Function1.run()
if flag2 == True:
Function2.run()
else:
pass
if flag3 == True:
Function3.run()
else:
pass
if someConditions == True:
brkFlag = True
Currently I want to change those flags with a GUI while the loop is running and am trying to do this with tkinter's Buttons and Checkboxes, but no luck so far.
I also can't use multithreading or multiprocessing as they will considerably slow down the speed of the loop (which is already barely acceptable as it is right now, because there are lots of calculations in each function and I need to show the results in a real-time fashion).
Edit: So it seems that there is no way other than doing multithreading/processing after all.
A simple way is to pass a mutable container containing the flags, for example a list:
flags = [flag2, flag3, someConditions ]
while brkFlag == False:
Function1.run(flags)
if flags[0] == True:
Function2.run(flags)
else:
pass
if flags[1] == True:
Function3.run(flags)
else:
pass
if someConditions == True: # or if flags[2] == True:
brkFlag = True
In the callee you implement more or less:
...
def run(flags):
...
flags[0] = True # set flag2
...

How to use a function as while loop condition?

I have the following code:
def funct():
print("beggining function")
a = int(input)
if a == 1:
return True
else:
return False
while funct():
#Rest of the code
Every time the while loop repeats it executes the function, so it prints "beggining function". I want to avoid this, what can I do?
A while <condition> loop works as follows:
it checks condition.
if condition evaluates to True, it executes the upcoming code one time. Then it goes back to 1.
if condition evaluates to False, it skips the upcoming code and goes through the rest of the code.
So what you are seeing here is the intended way for while to work.
To prevent this header from being printed every time, just move it out of the while:
def funct():
a = int(input)
if a == 1:
return True
return False # no need to check anymore
print("beggining function") # here
while funct():
#Rest of the code
Try to this
def funct():
print("beggining function")
a = int(input())
if a == 1:
return True
else:
return False
while funct() == 1:
funct()
you enter input 1 loop will continue...

Categories