Loops

Loops in Python

For Loops

for loops iterate over a collection of items, such as list or dict and run a block of code with each element from the collection.

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
  print(i)
# Output:
This image has an empty alt attribute; its file name is image-1.png

Range Function

range function – range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:

for i in range(10): 
  print(i)

#output:


gives the exact same result as before. Note that 10 is not printed as the range function excludes the number entered (known as the last number), range function has 3 parameters:

range(x) # one parameter means last number will be x(excluded)
range(x, y) # two parameters means 1st number will be x(included), last number will be y(excluded)
range(x, y, z) # three parameters means x will be first number(included), y will be the last number(excluded) and z will be the steps to the next number.

for i in range(10, 20):
  print(i)
# Output
for i in range(10, 30, 2):
  print(i)

#output:

While Loop

A while loop will cause the loop statements to be executed until the loop condition is false. The following code will execute the loop statements a total of 10 times.

i = 0 # assigning value to a variable
while i 10: # giving the condition where to terminate the loop
  print(i)
i = i + 2 # giving the condition to increase the value of i after every step

There are more operations of loops, We will understand those later, right now you have to understand a lot before diving into advance level of loops.

Previous||Next Chapter

Leave a Reply