USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Loops (for, while)

Lesson 10/35 | Study Time: 45 Min

Repetition is a core part of programming. Instead of writing the same line of code ten times, you write it once and let a loop handle the rest.

Loops allow Python to execute a block of code repeatedly, either for a fixed number of times or as long as a condition remains true. Python provides two types of loops: the for loop and the while loop, each suited for different situations.

The for Loop

The for loop is used when you know in advance how many times you want to repeat something. It iterates over a sequence such as a list, string, or range of numbers, and executes the block once for each item.

Syntax:

Example — Iterating over a list:



Example — Using range():

range() generates a sequence of numbers and is commonly used with for loops.





Example — Iterating over a string:


The while Loop

The while loop runs as long as a given condition remains True. It is used when you do not know in advance how many times the loop should run, it depends on a condition being met.

Syntax:

Example:


Each iteration increases count by 1. When count reaches 6, the condition becomes False and the loop stops.

Infinite Loops — What to Watch Out For

A while loop that never reaches a False condition runs forever. This is called an infinite loop and will freeze or crash your program.


Always make sure the condition inside a while loop will eventually become False, or use a break statement to exit.

Nested Loops

A loop inside another loop is called a nested loop. The inner loop completes all its iterations for every single iteration of the outer loop.




Nested loops are commonly used when working with tables, matrices, and multi-dimensional data in AI.

for vs while — When to Use Which


Practical Example 


Both loops produce the same result, the choice depends on the situation.


Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.