Python Loops


Loops are used to execute a block of code multiple times until it satisfy a perticular condition.

Also know as Iteration. In Python we can identify two main types of loops.


While Loop

We can use while loop to execute a block of code as long as the give condition is true.
i = 1 while i < 10: print(i) i = i + 1
"i" is a variable

As long as the value in the variable"i" is less than 10 (condition) it prints the value of "i".

There's no auto increment in while loop.

As you can identify in the abve code, identation(spacing) and : (colon) is important when using loops.


for Loop

We can use for loop to iterate over a sequence. (a string , list , tuple , dictionary )
for i in "Hello World": print(i)
"i" is a variable

It iterates over the string value and assign each charachter to the the variable "i".

As you can identify in the abve code, identation(spacing) and : (colon) is important when using loops.



for Loop with "range" function.

We can use range function to iterate over a code for a specified number of times.

The return values of "range" function by default starts from 0.

for i in range(5): print(i)
"i" is a variable

By deafault the increment is one(1).


We can use range function also to customize the start , stop and step values respectively.

Sructure

range(Start, Stop, Step):

for i in range(1, 10 , 2): print(i)
"i" is a variable

Values from 1 (start) to 10 (stop) and skip values by 2 (step).


To reverse the values(descending order), use negative numbers for the step value.

Example

range(1 , 10 , -1):

Output will numbers from 10 to 1(descending order).






Concept & Design by Code94 Labs