Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
77 views
in Technique[技术] by (71.8m points)

python - Difference in For loop and while loop?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...