What the difference between while and for loop [duplicate] - python

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.

Related

How to restart a code included into a function? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I would like to restart my python code from the beginning after a given "yes" input from the user, but I can't understand what I'm doing wrong here:
if input("Other questions? ") == 'yes' or 'yeah':
main()
else:
pass
my code is included within the function main().
Thanks for the help!!
You would probably do it with a while loop around the whole thing you want repeated, and as Loic RW said in the comments, just break out of the while loop:
while True:
# do whatever you want
# at the end, you ask your question:
if input("Other questions? ") in ['yes','yeah']:
# this will loop around again
pass
else:
# this will break out of the while loop
break

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 is this condition testing? [duplicate]

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):

for or while loop to do something n times [duplicate]

This question already has answers here:
More Pythonic Way to Run a Process X Times [closed]
(5 answers)
Closed 7 months ago.
In Python you have two fine ways to repeat some action more than once. One of them is while loop and the other - for loop. So let's have a look on two simple pieces of code:
for i in range(n):
do_sth()
And the other:
i = 0
while i < n:
do_sth()
i += 1
My question is which of them is better. Of course, the first one, which is very common in documentation examples and various pieces of code you could find around the Internet, is much more elegant and shorter, but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
So what do you think, which way is better?
but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?
That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.
In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).
This is lighter weight than xrange (and the while loop) since it doesn't even need to create the int objects. It also works equally well in Python2 and Python3
from itertools import repeat
for i in repeat(None, 10):
do_sth()
python3 & python2
just use range():
for _ in range(n):
# do something n times exactly
The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).
It is worth noting that in Python a for or while statement can have break, continue and else statements where:
break - terminates the loop
continue - moves on to the next time around the loop without executing following code this time around
else - is executed if the loop completed without any break statements being executed.
N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.
So the answer to your question is 'it all depends on what you are trying to do'!

Python loop that always executes at least once? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
do-while loop in Python?
How do I write a loop in Python that will always be executed at least once, with the test being performed after the first iteration? (different to the 20 or so python examples of for and while loops I found through google and python docs)
while True:
#loop body
if (!condition): break
You could try:
def loop_body():
# implicitly return None, which is false-ish, at the end
while loop_body() or condition: pass
But realistically I think I would do it the other way. In practice, you don't really need it that often anyway. (Even less often than you think; try to refactor in other ways.)

Categories

Resources