--Originally published at Hector Martinez Alcantara
Hi, I’m writing this post about the control flow tool called for loop. It’s used to repeat an action many times, but not only that, you can make a loop with specific conditions, and use it as a ‘foreach’ in C.
Another tool that we’re going to use is the range funtion that returns a list of a range of numbers.
I’m going to explain how the different uses of this for loop works.
First the sintaxis of the range tool:
range('initial number','last number range','conditional number')
Examples of use of range function:
#It can be used only as a quantity of numbers range(5) #The result is a list of numbers between 0 and 5 = [0,1,2,3,4] #Used as a range of numbers range(4,14) #The result is a list of the range of numbers between 4 and 14 = [4,5,6,7,8,9,10,11,12,13] #Used as a range of numbers with a jump condition range(0,100,10) #The result is a list of the range between 0 and 100 every 10 numbers = [0,10,20,30,40,50,60,70,80,90]
Now the sintaxis of the for tool:
for 'variable' in 'list' : #conditions
Examples of for loop function:
#Doing a quantity of actions for number in range(8): print("Hello") #The result is a print of the word 'Hello' 8 times #Using a range of numbers for number in range(10,20): print(number) #The result is a print of numbers from 10 to 19 #Using a range of numbers with a special jump condition for number in range(0,10,2): print(number) #The result is the pair numbers from 0 to 8 #Using a variable word="Hello" for letter in word: print(letter) #The result is a print of every letter in the word 'Hello' = ['H','e','l','l','o']
The explanation is that the for function takes every component in a list of components and use the component as the variable, for each component, the actions
![](https://31.media.tumblr.com/a001d4594a4af838fdc30068d4d6e9fd/tumblr_inline_nlc7dnCeSV1qf17wq.gif)
![](https://pixel.wp.com/b.gif?host=hectormtzblog.wordpress.com&blog=115238241&%23038;post=509&%23038;subd=hectormtzblog&%23038;ref=&%23038;feed=1)
Thank you for reading, any questions in comments.
Special thanks to The python documentation.
![](https://pixel.wp.com/b.gif?host=hectormtzblog.wordpress.com&blog=115238241&%23038;post=509&%23038;subd=hectormtzblog&%23038;ref=&%23038;feed=1)