Home > OS >  Which makes the loop easier ,the for loop or the while loop in python
Which makes the loop easier ,the for loop or the while loop in python

Time:01-04

we use for loop as well as while loop in python but which makes the program easier

please answer in sequential manner. I am facing problem in doing loop using while loop as it sometimes don't stop. so please suggest me that can i use for loop instead of while ,loop to make my program easier

CodePudding user response:

I use while loop only when I need to do infinite loop for example asking for user input. Most of the time I use for loop because it is easier for me

CodePudding user response:

As mentioned by someone else above, a for loop would usually be used when you want it to loop for a set amount of times. Whereas a while loop is normally used when dealing with a condition.

However you could use only while loops as they can do the same function as a for loop

CodePudding user response:

Its not just about making code easy there is a catch as well

The main difference between a for loop and a while loop is that a for loop is to iterate over a sequence of elements and execute a block of code for each element in the sequence. On the other hand, a while loop is to execute a block of code as long as a certain condition is true.

>>> string_some = "Hello"
>>> for i in string_some:
...     print(i)
...     string_some = "World"
...
H
e
l
l
o
>>> for i in string_some:
...     print(i)
...
W
o
r
l
d
>>>

Here, in the above cases value of i has been set to what for loop was set to iterate while the same won't be same for while loop.

>>> some_string = "Hello"
>>> cnt = 0
>>> while cnt <= len(some_string):
...     print(some_string[cnt])
...     some_string = "World"
...     cnt  = 1
...
H
o
r
l
d
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: string index out of range
>>>
  • Related