0% found this document useful (0 votes)
2 views5 pages

Loops in Python 1

The document provides an overview of loops in Python, including while loops, for loops, and nested loops. It includes various examples demonstrating the syntax and usage of these loops, such as printing sequences, messages, and patterns. Additionally, it shows how to use loops with user input to create dynamic outputs.

Uploaded by

singhanshu3788
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)
2 views5 pages

Loops in Python 1

The document provides an overview of loops in Python, including while loops, for loops, and nested loops. It includes various examples demonstrating the syntax and usage of these loops, such as printing sequences, messages, and patterns. Additionally, it shows how to use loops with user input to create dynamic outputs.

Uploaded by

singhanshu3788
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

Loops in Python

Types of Loops in Python

➢ While Loops in Python

➢ For Loops in Python

➢ Nested Loops in Python

Examples

for loop (basic)

for i in range(5):

print(i)

for loop with start and end

for i in range(1, 6):

print(i)

for loop to print a message multiple times

for i in range(3):
print("Hello")

Hello

Hello

Hello

while loop (basic)

i = 1

while i <= 5:

print(i)

i += 1

while loop to print a word

i = 0

while i < 3:

print("Python")

i += 1

Python

Python

Python
Loop with user input

n = int(input("Enter a number: "))

for i in range(1, n + 1):

print(i)

Basic Nested for Loop

for i in range(1, 4):

for j in range(1, 4):

print(i, j)

1 1

1 2

1 3

2 1

2 2

2 3

3 1

3 2

3 3
Nested Loop – Print a Square Pattern

for i in range(3):

for j in range(3):

print("*", end=" ")

print()

* * *

* * *

* * *

Nested Loop – Print a Number Pattern

for i in range(1, 4):

for j in range(1, i + 1):

print(i, end=" ")

print()

2 2

3 3 3

Nested while Loop

i = 1

while i <= 3:

j = 1

while j <= 3:

print(i, j)

j += 1

i += 1

1 1

1 2

1 3
2 1

2 2

2 3

3 1

3 2

3 3

Nested Loop with User Input

n = int(input("Enter number of rows: "))

for i in range(1, n + 1):

for j in range(1, i + 1):

print("*", end=" ")

print()

* *

* * *

* * * *

You might also like