What is this condition testing? [duplicate] - python

This question already has answers here:
What does "while True" mean in Python?
(18 answers)
Closed 9 years ago.
in the following program:
count = 0
while True:
count += 1
if count>10:
break
if count==5:
continue
print(count)
what exactly is while True testing? And can there ever be a while false condition, if so what would that be testing?

while True: is an infinite loop. It will only ever be broken by break, return, or an exception being raised (in your case the first).

It is an infinite loop. It tests if True is.. true, which it always is.
It is the conditions in the loop that end it; the break statement breaks out of the infinite loop here, not the while condition.
Note that the continue statement merely skips the remainder of the loop iteration and skips to the next.
Other events that'd end the loop are a return (provided the loop is part of a function), or an if an exception was raised.

This will create an infinite loop, most likely causing your program to crash. If you would like to stop the loop, use return. You're code is pretty much counting up to 10, then stopping, as seen in
if count>10:
break
a better way of doing this would be to use a for loop
for count in range(0, 10):

Related

else in the end of for and while loops

who can say me:
What is the difference between writing code inside else or just after the loops?
for x in range(6):
print('hello')
print('bye')
or
for x in range(6):
print('hello')
else:
print('bye')
From for/else documentation:
The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.
This means that in your specific example there is no difference in using else or not.
In the second example you're using conditional statement, Whereas in the first scenario after the loop completes, It automatically executes the next line.
Basically your post is an example of getting same result with alternative solutions.
Though your first solution can be considered as valid practice comparing with second one.
Although I would suggest you to read this article before posting any questions on stack overflow.

What the difference between while and for loop [duplicate]

This question already has answers here:
When to use "while" or "for" in Python
(10 answers)
Closed 1 year ago.
There is a really differ between while and for in python? Or can I use anyone I want?
And my second question :-
persons['alic', 'sam', 'rain']
first_name = 'mike'
for first_name in persons :
#when the program runs for the first time
#what is the value of first_name?
#is it 'mike',or its value is Null??
print(first_name)
And thanks.
In general, a for in loop is useful for iteration over a known set and the number of iterations is predetermined. A while loop is generally used when the exit condition is a change of state, not a predetermined length.
Common use cases for while loops include:
Running the main loop of a program until a keyboard interrupt:
try:
while True:
break
except KeyboardInterrupt:
print("Press Ctrl-C to terminate while statement")
pass
Finding the last node in a list of references:
while(node is not None):
node = node.next()
This question is answered well in this stackoverflow
Pulling out the information:
while loop - used for looping until a condition is satisfied and when it is unsure how many times the code should be in loop
for loop - used for looping until a condition is satisfied but it is used when you know how many times the code needs to be in loop
do while loop - executes the content of the loop once before checking the condition of the while.

Difference in For loop and while loop? [duplicate]

This question already has answers here:
When to use "while" or "for" in Python
(10 answers)
Closed 2 years ago.
Can someone explain me difference between for loop and while loop in easy language and with some example ?
I have trying to go through some websites or videos but the language may be little complicated for me
They mostly do the same thing, or they can be configured to do the same thing. But generally, for loop is used if we know how long the loop should run, and while is used if we need to loop "while" a condition is satisfied.
for i in range(0,10):
print("hello")
This will print "hello" 10 times, but if we want to print "hello" until a condition changes, we use while:
while(i != 20):
print("hello")
This will loop forever until i is changed to 20.
Both for loop and while loop are used to excute one or more lines of code certain number of times. The main differences are as follows.
Syntax:
While loop:
while(condtion) {
//statements to excute.
}
For loop:
for(intialization; condition; Increment or decrement){
// statements to be excuted.
}
There are few variations we can do with for loop.
Such as all three parts of for loop are optional. That means you can also have a loop like this.
for(;;) which is nothing but an infinite loop.
For initialization there can be multiple statements.
for(i =0, j =0;i<20;i++)
Similarly for the third component there can be any expression and not necessarily increment or decrement.
for(i =0;i<10;i = i * 2)
Working:
In while loop first of all the condition expression is evaluated and if it is true then the body of the loop is excuted. Then control again evaluate the condition expression. This goes on untill condition becomes false.

What's the difference between pass and continue in python [duplicate]

This question already has answers here:
Is there a difference between "pass" and "continue" in a for loop in Python?
(13 answers)
Closed 5 years ago.
My test shows that both pass and continue can be used equivalently to construct a empty for-loop for test purpose. Are there any difference between them?
The pass keyword is a "no-operation" keyword. It does exactly nothing. It's often used as a placeholder for code which will be added later:
if response == "yes":
pass # add "yes" code later.
The continue keyword, on the other hand, is used to restart a loop at the control point, such as with:
for i in range(10):
if i % 2 == 0:
continue
print(i)
That loop will only output the odd numbers since continue returns to the loop control statement (for) for iterations where i is even.
Contrast that with the exact same code, but using pass in place of continue:
for i in range(10):
if i % 2 == 0:
pass
print(i)
That loop prints all the numbers in the range, since pass does not return to the loop control statement for even (or any) values of i. It simply drops through to the print statement.
In terms of an empty for loop, you're correct that they're functionally identical. You can use either of:
for i in range(10):
pass
for i in range(10):
continue
pass does nothing (no operation), while continue make control flow to continue to next cycle of the loop.
If the loop contains only a single statement, a pass or continue won't make any difference. But if there are multiple statements, then it matters:
for item in my_list:
pass
print(item) #This will be executed
for item in my_list:
continue
print(item) #won't be executed
Basically, the pass statement do nothing, while the continue statement will restart the loop.
But in your case:
for item in my_list:
pass
#Since there's nothing after pass, the loop is finished.
for item in my_list:
continue
#You're restarting the loop
There difference is not very visible.
Hope this helps!
continue means "skip to the end of the loop body". If it's a while loop, the loop continues on to the loop test; if it's a for loop, the loop continues on to the next element of whatever it's iterating over.
pass does absolutely nothing. It exists because you have to have something in the body of an empty block statement, and pass is more readable than executing 1 or None as a statement for that purpose.
This will lead to an infinite loop if you use continue:
i = 0
while i<1:
continue
i = i + 1
print i
because continue only goes to the next iteration. But pass will work for this case.
pass and continue both work, but may create infinite loops.
For example, the following code will create infinite loop.
i = 0
while i<100:
continue # replacing continue with pass still creates an infinite loop.
If you want to avoid this (perhaps you intend to modify i withe loop, but you haven't written the code yet), use break.

Flow control after breaking out of while loop in Python

I am pretty new to both programming and Python. A few times now, I have created what feels like an awkward program flow, and I am wondering if I am following best practices. This is conceptually what I have wanted to do:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
now do a thing once, but only if you never broke out of the loop above
What I've ended up doing works, but feels off somehow:
def pseudocode():
while some condition is true:
do some stuff
if some condition is met:
some_condition_met = True
break out of the while loop
if some_condition_met is False:
do a thing
Is there a better way?
You're looking for while-else loop:
def pseudocode():
while some condition is true:
do some stuff
if a condition is met:
break out of the while loop
else:
now do a thing once, but only if you never broke out of the loop above
From docs:
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite.
Use an else clause to the while loop:
while some_condition:
do_stuff()
if a_condition_is_met:
break
else:
executed_when_never_broken
See the while statement documentation:
A break statement executed in the first suite terminates the loop without executing the else clause’s suite.
If you think about it, you might already have a perfectly good condition to use without setting a flag: the condition at the top of the while loop (or, rather, the not of it). Assuming you don't change the truthiness of your condition during the same iteration as a break, this gives you:
while something:
do_stuff()
if something_else:
break
if not something:
more_stuff()
This makes sense if you think of while as a repeated if: instead of happening once, a while keeps going until the condition becomes falsey.
But, like the other answers have mentioned, the analogy goes further: just like you don't have to spell all your ifs as
if a:
a_stuff()
if not a:
b_stuff()
while accepts an else that is executed if the condition at the top is tested and found to be falsey. So,
while something:
do_stuff()
if something_else:
break
else:
more_stuff()
And, same as the if/else case, this doesn't imply any further tests of the condition than what would happen anyway. In the same way that an else attached to if a won't run if the true-branch makes a falsey, an else attached to a while will never run after a break since that explicitly skips ever checking the condition again. This makes the else: equivalent to a decicated flag in every case.
This also extends to for loops, even though the analogy breaks - but it executes under similar enough rules: the else is run if the loop ends by having run its course rather than hitting a break.

Categories

Resources