For Loops

--Originally published at Sierra's Blog

Foor loops in python are similar to while loops but with a small difference:

While loops are used when you don’t know the exactly amount of times that your code needs to be repeated, for example, a calculator that when it finishes doing the stuff that the user asked for asks if he wants to do something else.

For loops are the opposite in this case because you, as the programmer, already know how many times do you need the code to be reapeated.

How do I call it in python?

for + Variable + in + range(x1,x2):

for – you need to start with that word

Variable – is going to be the Variable that when the for loop ends it’s going to change

*If the variable is an integer – at the end of the loop it will become variable + 1.

*if the variable is in a list – at the end of the loop it will jump into the next string on the list.

in – you need to add the word in.

range()  – the range…

for x in range (0,100):
print(“do this.”)

this program is going to repeat the phrase “do this” 100 times.

Another example with list instead of range:

Food = [“Meat”,”Ham”,”banana”, “Apple”, “Fish”]

for food in Food:
print (food)

this will print:

Meat

Ham

Banana

Apple

Fish

Notes:

Food is the name of the list.

food is the variable’s name of the strings inside the list.