Yes!
Once the condition has been met, use break:
while True:
someVar = str.lower(input())
if someVar == 'yes':
someVar = True
break
if someVar == 'no':
someVar = False
break
You can also use while False with:
met = True
while met:
someVar = str.lower(input())
if someVar == 'yes':
someVar = True
break
if someVar == 'no':
someVar = False
break
Since all strings are True, use another variable to store either True or False. Once met is false, then the loop will break.
Yes!
Once the condition has been met, use break:
while True:
someVar = str.lower(input())
if someVar == 'yes':
someVar = True
break
if someVar == 'no':
someVar = False
break
You can also use while False with:
met = True
while met:
someVar = str.lower(input())
if someVar == 'yes':
someVar = True
break
if someVar == 'no':
someVar = False
break
Since all strings are True, use another variable to store either True or False. Once met is false, then the loop will break.
This should work
someVar = None
while (True):
someVar = str.lower(input())
if someVar == 'yes':
someVar = True
break
elif someVar == 'no':
someVar = False
break
Use break to exit a loop:
while True:
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
checking = ser.readline();
if checking.find(",,,,"):
print "not locked yet"
else:
print "locked and loaded"
break
The True and False line didn't do anything in your code; they are just referencing the built-in boolean values without assigning them anywhere.
You can use a variable as condition for your while loop instead of just while True. That way you can change the condition.
So instead of having this code:
while True:
...
if ...:
True
else:
False
... try this:
keepGoing = True
while keepGoing:
ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
checking = ser.readline();
if checking.find(",,,,"):
print "not locked yet"
keepGoing = True
else:
keepGoing = False
print "locked and loaded"
EDIT:
Or as another answerer suggests, you can just break out of the loop :)
Videos
If you want 'while false' functionality, you need not. Try while not fn: instead.
The condition is the loop is actually a "pre-" condition (as opposed to post-condition "do-while" loop in, say, C). It tests the condition for each iteration including the first one.
On first iteration the condition is false, thus the loop is ended immediately.
One way to avoid the extra line:
while True
door = input("Do you want to open the door? Enter yes or no: ").lower()
if door in ("yes", "no"):
break
print("Invalid answer.")
Or if you do this a lot make a helper function.
def get_input(prompt, error, choices):
while True:
answer = input(f"{prompt} Enter {', '.join(choices)}: ")
if answer in choices:
return answer
print(error)
Example usage:
door = get_input("Do you want to open the door?", "Invalid answer.", ("yes", "no"))
if door == "yes":
print("You try to twist open the doorknob but it is locked.")
else:
print("You decide not to open the door.")
while True:
answer = ("Enter yes or no: ").lower()
if answer in ["yes", "no"]:
break
print("Invalid answer.")
# loop will repeat again
Have a look on a code below:
def repeat():
correct_value = False
# while not False so the correct_value = True
# so it is an equivalent of -> while True:
# while True will always run
while not correct_value:
try:
guess = int(input())
except ValueError:
print("Please Enter a Number")
else:
correct_value = True
return guess
Why does "while not false" even loops in the first place?
It loops because of the double negation which is always True.
And what's the actual really keeps the loop running?
Exactly the same while not False, which results in while True
not False means True, that's why it works in the first place. Exceptional handling is used for purposes like this. It tries to take an integer input, if the user does not enter an integer, it throws an error which is handled by the except block.
if the user does give an integer, correct_value becomes true, so not True means false so the loop terminates and the function returns the input.
Using sets will be screaming fast if you have any volume of data
If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.
MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])
while not MyList.isdisjoint(MyOper):
print "No boolean Operator"
http://docs.python.org/library/stdtypes.html#set.isdisjoint
The expression 'AND' and 'OR' and 'NOT' always evaluates to 'NOT', so you are effectively doing
while 'NOT' not in some_list:
print 'No boolean operator'
You can either check separately for all of them
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
or use sets
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
A while loop will execute while the given expression is True. In your case, the given expression is not found. Since found starts off as False, not found is of course True, hence the loop executes and will continue to execute until found is set to True, at which point not found will be False.
My advice would be to not rewrite this - it is actually very readable as it is. You are saying that while you have not found something, keep looking.
If while not found seems unintuitive, you should probably just get used to it. It's a common Python idiom and will seem very intuitive after a while (pun intended).
If you want more readable code, though, I would get rid of the found variable entirely and use break to terminate the loop:
def main():
randomNumber = randint(1,100)
while True:
userGuess = input("")
if userGuess == randomNumber:
print "You win."
break
# Code here will run only if the break isn't executed.
# You don't need the elif any more.
It is a matter of personal preference: some people like to use a flag variable to terminate a loop; I prefer the simplicity of an explicit break in code like this.
Since your while not pair: loop did not work, you have found an important difference: pair == False only tests true if pair is set to 0 or False (the only two values that test as equal to False), while while not pair tests for any truth value (inverting that value).
You appear to have assigned some other value to pair that is neither of those two values causing the behaviour to change (a truthy value to break out early, or a falsey value to keep the loop going longer than expected).
It is that difference that is one of the reasons why the Python style guide recommends you always use if true_expression or if not false_expression rather than use == True or == False:
Don't compare boolean values to
TrueorFalseusing==.Yes:
if greeting:
No:if greeting == True:
Worse:if greeting is True:
Last but not least, for a while ...: loop that simply tests against a single boolean flag (while flag: or while not pair:), consider using while True: and break instead. So rather than do:
flag = True
while flag:
# ...
if condition:
flag = False
do this instead:
while True:
# ...
if condition:
break
Aside from actually having little or no difference at all,
Using False in a == comparison allows usage of 0 and 1.
0 == False
1 == True
Using not is inversion of current value.
not 0 == True
not 1 == False
not False == True
You can use in your program assuming that pair can only contain boolean values:
while not pair:
If you however still want to use a variable that can contain both boolean and number, you can use:
while pair is False:
To expand on what others have already stated, run on these lines
if loop == "y" :
run = True
elif loop == "n" :
run = False
are not referring to the same run defined by
#Can be set to True if while (run != True) is set to while (run == True).
run = False
run in the cont function is a local variable to your function, not the globaly defined run.
There are a couple (at least) ways to fix this. The preferred (imo) way to do it is have cont return a new value to be assigned to run. That would look like
#Defining cont(). Ask for imput and error handling.
def cont(_run):
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
return _run
elif loop == "n" :
return not _run
else :
print("You did not enter a valid response, please try again.")
return cont(_run)
...
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
run = cont(run)
The other (less preferred) way would be to use the global run variable inside of your cont function. This is achieved using the global keyword.
That would look like this:
#Defining cont(). Ask for imput and error handling.
def cont():
global run
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
** Couple side notes
In my first example I return _run when the value is y and not _run when the value is n. This allows you to change you initial run value to be True, and change the while condition without having to change the cont function itself.
You don't need to actually change the run value at all if you use the global and the user enters n since you exit before the function returns.
You might be better off changing your if conditional checks to
if loop in ("yes", "y"):
if loop in ("no", "n"):
since lots of people don't read full instructions :)
The run inside the cont function is a local variable. Changing its value has no effect on the global variable that the while loop refers to.
while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're likely to encounter have equivalent idioms.
Note that most languages usually have some mechanism for breaking out of the loop early. In the case of Python it's the break statement in the cmd == 'e' case of the sample in your question.
my question: while WHAT is True?
While True is True.
The while loop will run as long as the conditional expression evaluates to True.
Since True always evaluates to True, the loop will run indefinitely, until something within the loop returns or breaks.
A while loop checks the condition (well, the expression) behind the while before each iteration and stops executing the loop body when the condition is False.
So while False means that the loop body will never execute. Everything inside the loop is "dead code". Python-3.x will go so far that it "optimizes" the while-loop away because of that:
def func():
i = 1
while False:
if i % 5 == 0:
break
i = i + 2
print(i)
import dis
dis.dis(func)
Gives the following:
Line Bytecode
2 0 LOAD_CONST 1 (1)
3 STORE_FAST 0 (i)
7 6 LOAD_GLOBAL 0 (print)
9 LOAD_FAST 0 (i)
12 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
15 POP_TOP
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
That means the compiled function won't even know there has been a while loop (no instructions for line 3-6!), because there is no way that the while-loop could be executed.
while True:
means that it will loop forever.
while False:
means it won't execute.
In Python 3.x, works fine.
Maybe you're compiling with python 2.x. In that case, you need to use 'raw_input' instead of 'input', but I don't recommend raw_input (it's deprecated in Python3).
Try Python 3.x.
PS: Also, I'd replace 'self' with other variable name. Self is used in classes.
It doesnt break. Please verify your solution. Here is modified code
database = {
"hello": "Nice to meet you. What can I do for you?",
"hi": "Nice to meet you. What can I do for you?",
"hey": "Nice to meet you. What can I do for you?",
"goodbye": "Bye. See you next time!"
}
def make_response(self):
self = self.lower()
value = database.get(self, "Sorry I dont understand")
print(value)
def robot():
print('Welcome to robot.py')
print('What can I do for you?')
while True:
query = input('>')
if query == "goodbye":
value = database.get(query)
print(value)
break
else:
make_response(query)
robot()
while-else works the following way: If the while condition is not satisfied, then the else is executed.
So, when you type "quit" in the program, then if command == "start": and elif command == "stop": conditions are not satisfied.
So, the else is executed, which prints I don't understand that.
Now, again the condition for while loop is checked : command != "quit"
But, this condition is False, as the value of command is now "quit".
So,
else:
print("Game exited")
is executed, and thus your output becomes
I don't understand that
Game exited
while command != "quit":
command = input("Command: ")
if command == "start":
print("Car ready to go")
elif command == "stop":
print("Car stopped")
else:
print("I don't understand that")
else:
print("Game exited")
Looking at your code, you get input "quit", then it comes down to first if(not true)->next elif(not true)->next else(true)->print("car stopped")->next while(not true)->finish loop and go to "i don't understand that"
Change the code like this:
while command != "quit":
command = input("Command: ")
if command == "start":
print("Car ready to go")
elif command == "stop":
print("Car stopped")
elif command != "quit":
print("I don't understand that")
else:
print("Game exited")
while swag: will run while swag is "truthy", which it will be while swag is True, and will not be when you set swag to False.
Does while swag - check if swag exists or if swag is True
It checks if swag is True (or "truthy", I should say). And yes, the loop will exit after 3 iterations because i=i+1 must be executed 3 times until i == 3 and (by the if-statement) swag is set to False, at which point the loop will exit.
But why not check this yourself?
swag = True
i = 0
while swag:
i=i+1
print(swag)
if i == 3:
swag = False
True True True