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 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.
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.


Both loops produce the same result, the choice depends on the situation.
We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.