While vs For in Python

--Originally published at Ed_Alita

The backgroud

This two funtions are used to create loop that inside is a code that you wish to repeat it self. The question is if they are the same how to choose between them. I will explain each one and then teach you how to choose between them.

For

This funtion repeats itself only the times that you indicate or until it condition is not longer true.

Lets see this example:

for1

This code for each letter in the word Python will run the code.

Let’s see what it does.

forex1

While

This funtion repeats itself until it make false it’s value.

This is the logic that While follows:

while1

The next Example will make it clear:

while2

This program will run each time until count be 9. Lets see what it does:

whileex1

Which one I use?

The use of each one depends on what you need. Lets see if you know how many times the user will put the correct answer use for but if you don’t know how many times you can use a infinite while.

The material use can be seen here:

https://docs.python.org/3/reference/compound_stmts.html#while