When to use while or for in Python

0 votes

I am finding problems in when I should use a while loop or a for loop in Python. It looks like people prefer using a for loop (less code lines?). Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I have read so far made me think there are big differences between them.

Feb 9 in Python by Dev
• 6,000 points
18 views

1 answer to this question.

0 votes

while and for are both flow control statements. 
for loops are used when we know the number of iterations, while loops are used when number of iterations are unknown, while loop ends when some condition is met.

for loops are easier to read and also easier to understand as compared to while loops.

for num in range(5):
    print (num)

Output
 

0
1
2
3
4
num = 0
while num <= 5:
    print (num)
    num = num + 1

Output

0
1
2
3
4
5

In case of while loops some condition must be met, else it will result in an infinite loop.
 

answered Feb 9 by Nandini
• 5,480 points

Related Questions In Python

0 votes
1 answer

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

Yes, there is a significant distinction between ...READ MORE

answered Feb 9 in Python by CoolCoder
• 4,360 points
40 views
0 votes
1 answer

When to use %r instead of %s in Python? [duplicate]

The %s specifier converts the object using ...READ MORE

answered Aug 2, 2018 in Python by bug_seeker
• 15,530 points
350 views
0 votes
1 answer

When to use file vs open in Python?

File() has been removed since Python 3.0 ...READ MORE

answered Oct 30, 2018 in Python by SDeb
• 13,300 points
452 views
0 votes
1 answer

How do I use urllib to see if a website is 404 or 200 in Python?

For Python 3, try doing this: import urllib.request, ...READ MORE

answered Nov 29, 2018 in Python by Nymeria
• 3,540 points

edited Dec 11, 2018 by Nymeria 10,305 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,756 views
0 votes
1 answer
0 votes
1 answer

What is the use of "assert" in Python?

The statement assert exists in almost every programming ...READ MORE

answered Feb 7 in Python by Nandini
• 5,480 points
23 views
0 votes
1 answer

Is there a way to create multiline comments in Python?

In Python, you can use '''  some ...READ MORE

answered Feb 7 in Python by Nandini
• 5,480 points
14 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP