When to Use "While" or "For" in Python

When to use while or for in Python

Yes, there is a huge difference between while and for.

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

It isn't preference. It's a question of what your data structures are.

Often, we represent the values we want to process as a range (an actual list), or xrange (which generates the values) (Edit: In Python 3, range is now a generator and behaves like the old xrange function. xrange has been removed from Python 3). This gives us a data structure tailor-made for the for statement.

Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.

In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The sorted and enumerate functions apply a transformation on an iterable that fits naturally with the for statement.

If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use while.

Using or in a while loop (Python)

The condition of your while loop will ALWAYS be true. In order for it to be false, variable1 must equal "1", "2", and "3", which is impossible for a single string.

>>> variable1 == "1"
>>>
>>> variable1 != "1"
False
>>> variable1 != "2"
True
>>> variable1 != "3"
True
>>> False or True or True
True # So the loop will continue execution

Do you want your while loop to exit if variable1 equals "1", "2", or "3"?

while not (variable1 == "1" or variable1 == "2" or variable1 == "3"):

If variable1 equals either "1", "2", or "3", then it's useful to imagine how the condition will be resolved:

while not (True or False or False):

while not (True):

while False: # Exit

Why does python use 'else' after for and while loops?

It's a strange construct even to seasoned Python coders. When used in conjunction with for-loops it basically means "find some item in the iterable, else if none was found do ...". As in:

found_obj = None
for obj in objects:
if obj.key == search_key:
found_obj = obj
break
else:
print('No object found.')

But anytime you see this construct, a better alternative is to either encapsulate the search in a function:

def find_obj(search_key):
for obj in objects:
if obj.key == search_key:
return obj

Or use a list comprehension:

matching_objs = [o for o in objects if o.key == search_key]
if matching_objs:
print('Found {}'.format(matching_objs[0]))
else:
print('No object found.')

It is not semantically equivalent to the other two versions, but works good enough in non-performance critical code where it doesn't matter whether you iterate the whole list or not. Others may disagree, but I personally would avoid ever using the for-else or while-else blocks in production code.

See also [Python-ideas] Summary of for...else threads

Why avoid while loops?

The advice seems poor to me. When you're iterating over some kind of collection, it is usually better to use one of Python's iteration tools, but that doesn't mean that while is always wrong. There are lots of cases where you're not iterating over any kind of collection.

For example:

def gcd(m, n):
"Return the greatest common divisor of m and n."
while n != 0:
m, n = n, m % n
return m

You could change this to:

def gcd(m, n):
"Return the greatest common divisor of m and n."
while True:
if n == 0:
return m
m, n = n, m % n

but is that really an improvement? I think not.

How to properly use while not loops in python?

The best explanation for while not guessed is that it is essentially saying "while guessed is not equal to true". This is to say it is basically "while guessed is false." So the while loop will run for as long as guessed is false and tries > 0. However, if guess is every made to be true, then the while loop will stop running.

The key thing is that not doesn't meaning negation in this sense. It is just meaning that the while loop runs as long as the value of guessed is false and NOT true. I understand the confusion in this but it is an important fact to know.

when to use while loop rather than for loop

One main difference is while loops are best suited when you do not know ahead of time the number of iterations that you need to do. When you know this before entering the loop you can use for loop.



Related Topics



Leave a reply



Submit