0% found this document useful (0 votes)
0 views3 pages

Python Loops Guide

The document explains Python loops, specifically 'for' and 'while' loops, and their usage with the range() function. It includes examples for printing numbers, using break and continue statements, and demonstrates nested loops. A summary table is provided to highlight the use cases and syntax for each loop type.

Uploaded by

macbox029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views3 pages

Python Loops Guide

The document explains Python loops, specifically 'for' and 'while' loops, and their usage with the range() function. It includes examples for printing numbers, using break and continue statements, and demonstrates nested loops. A summary table is provided to highlight the use cases and syntax for each loop type.

Uploaded by

macbox029
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python Loops and Range - Explained

1. What is a Loop?

A loop is used to repeat a block of code multiple times. Python has two types of loops: 'for' and 'while'.

2. Python for loop & range()

Format: for variable in range(start, stop, step):

# code block

Example 1: Print numbers from 1 to 5

for i in range(1, 6):

print(i)

Example 2: Even numbers from 2 to 10

for i in range(2, 11, 2):

print(i)

Note:

- range(stop): from 0 to stop-1

- range(start, stop): from start to stop-1

- range(start, stop, step): increment by step

3. Python while loop

Format:

initialization

while condition:

# code block

increment/decrement

Example: Print numbers from 1 to 5

i=1

while i <= 5:
Python Loops and Range - Explained

print(i)

i += 1

4. break and continue

break: exits the loop immediately

for i in range(5):

if i == 3:

break

print(i)

continue: skips the current iteration

for i in range(5):

if i == 2:

continue

print(i)

5. Nested Loops

Loops inside another loop.

Example:

for i in range(1, 4):

for j in range(1, 3):

print(f"i={i}, j={j}")

6. Summary Table

| Loop Type | Use Case | Example Syntax |

|-----------|-----------------------|----------------------------|

| for | Fixed repetitions | for i in range(5): |

| while | Condition-based | while i <= 10: |

| range() | Generates number list | range(start, stop, step) |


Python Loops and Range - Explained

| break | Exit loop early | if condition: break |

| continue | Skip iteration | if condition: continue |

You might also like