![]() |
Loops in Python |
Definition of Loops:-
Loops means repeating something over and over until a particular condition is satisfied.
There are two types of Loops in Python:-
![]() |
For Loop |
for
Loop in PythonSyntax:
Explanation:
for
: Keyword to start the loop.variable
: The name that will hold the current value of the loop at each iteration.in range(start, stop, step)
:start
: Where the loop starts (default is 0).stop
: The number the loop goes up to (but doesn't include).step
: How much to increase the variable after each loop (default is 1).
Example:
- This will print numbers 0 to 4.

While Loop
2. while
Loop in Python

Syntax:
Explanation:
while
: Keyword to start the loop.condition
: This is a statement that is checked before each loop. If it’s True, the loop runs. If it’s False, the loop stops.- The code inside the loop will keep repeating as long as the condition is
True
.
Example:
- This prints 0 to 4. The loop continues as long as
i
is less than 5.
Tips to Remember Python Loop Syntax:
for
loop: Think of looping through a sequence. In Python,for
is often used withrange()
, which creates a list of numbers.- Remember:
for variable in range(start, stop):
- Remember:
while
loop: Think of repeating something while a condition is true.- Remember:
while condition:
- Remember:
Quick Tricks to Remember:
- Indentation: Python uses spaces (indentation) to define the block of code inside the loop. No curly braces
{}
like other languages. - Colons (
:
): After the loop condition (whetherfor
orwhile
), always remember the colon:
. This tells Python that the next lines are part of the loop.
Example to Remember Both Loops:
for
loop:
while
loop:
To summarize:
for
loop: Use it when you know how many times you want to repeat the loop (like counting).while
loop: Use it when you want to repeat the loop as long as a condition is true.
Note:
Once you understand the logic behind each loop, remembering the syntax becomes easy. The key is practicing and writing loops frequently.
No comments:
Post a Comment