When to use "while" or "for" in Python

Pybeginner
By -
0


Let's try to see in which situation it is better to use the while or for loop, yes, there is a huge difference between while and for. It's not preference. It's a matter of what your data structures are.



Thestatement for iterates through a collection or iterable object or generator function.


Thestatement while simply loops until a condition is False.



The for is the most Python choice for iterating a list as it is simpler and easier to read.


For example this:


 

for i in range(11):

    print(i)

 


is much simpler and easier to read than this:


 

i = 0

 

while i <= 10:

    print(i)

    i = i + 1

   




for loop is used when you have an iteration defined (the number of iterations is known).


Usage example:


- Iterate through a loop with defined range: 


for i in range(23):


- Iterate through collections (string, list, set, tuple, dictionary): 


for books in books:



while loop is an indefinite iteration that is used when a loop repeats itself an unknown number of times and ends when some condition is met.


Note that in the case of a while loop, the indented body of the loop must modify at least one variable in the test condition, otherwise the result is an infinite loop.


Usage example:


- The code block execution requires the user to enter the specified input: 

while input == specified_input:


- When you have a condition with comparison operators: 

while counter < limit and stop != False:


 

Tags:

Post a Comment

0Comments

Post a Comment (0)