Skip to content

Latest commit

 

History

History
480 lines (354 loc) · 5.71 KB

README.md

File metadata and controls

480 lines (354 loc) · 5.71 KB

Chapter 5: Loops and Iteration

Table of Contents

While Loop

The while loop repeatedly executes a block of code as long as a specified condition is true.

Basic While Loop

i = 1

while (i <= 5):
    print(f"{i}. Python")
    i += 1

print("END")

Output:

1. Python
2. Python
3. Python
4. Python
5. Python
END

Example: Sum of First N Natural Numbers

n = int(input("n: "))  # 4

i = 1
sum = 0

while(i <= n):
    sum += i
    i += 1

print(sum)

Output:

Enter n: 4
10

Example: Iterating Over a String

s = input("S: ")

i = 0

while(i < len(s)):
    print(s[i])
    i += 1

Output:

Enter S: Python
P
y
t
h
o
n

Example: Printing a Pattern

h = int(input("H: "))
row_no = 1

while(row_no <= h):
    print('*' * row_no)
    row_no += 1

Output:

Enter H: 4
*
**
***
****

Example: Calculating Factorial

n = int(input("N: "))
i = 1
f = 1

while(i <= n):
    f = f * i
    i += 1

print(f)

Output:

Enter N: 5
120

Example: Checking Prime Number

n = int(input("N: "))

divisor_count = 0
i = 1

while(i <= n):
    if(n % i == 0):
        divisor_count += 1
    i += 1

if(divisor_count == 1):
    print('Neither prime nor composite')
else:
    print('Prime' if divisor_count == 2 else 'Composite')

Output:

Enter N: 7
Prime

For Loop

The for loop iterates over a sequence (such as a list, tuple, or string) and executes a block of code for each item in the sequence.

Basic For Loop

l = [1, 2, 3]

for a in l:
    print(a)

Output:

1
2
3

Example: Iterating Over a Dictionary

d = {
    '(1)': 'one',
    '(2)': 'two',
    '(3)': 'three'
}

for a in d:
    print(a, d[a])

Output:

(1) one
(2) two
(3) three

Example: Iterating Over a String

s = "Python"

for a in s:
    print(a)

Output:

P
y
t
h
o
n

Example: Using Range

The range function generates a sequence of numbers, which is useful for iterating a specific number of times.

for i in range(1, 10):
    print(i)

Output:

1
2
3
4
5
6
7
8
9

Example: Checking Prime Number

n = int(input('N: '))

is_prime = True

for i in range(2, n):
    if(n % i == 0):
        is_prime = False

print('Prime' if is_prime else 'Composite')

Output:

Enter N: 7
Prime

Nested Loops

You can use loops inside other loops. These are called nested loops.

Basic Nested Loop

for i in range(1, 5):
    for j in range(1, 4):
        print(i, j)

Output:

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
4 1
4 2
4 3

Example: Iterating Over a Matrix

A matrix is a two-dimensional array. You can use nested loops to iterate over each element.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for i in range(len(matrix)):
    for j in range(len(matrix[0])):
        print(f"matrix[{i}][{j}] =", matrix[i][j])

Output:

matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
matrix[2][0] = 7
matrix[2][1] = 8
matrix[2][2] = 9

Break and Continue

The break statement is used to exit a loop prematurely, and the continue statement is used to skip the current iteration and continue with the next iteration.

Break Statement

for i in range(1, 11):
    print(i)
    if(i == 4):
        break
    print("after break")

Output:

1
after break
2
after break
3
after break
4

Continue Statement

for i in range(1, 11):
    if(i % 2 == 0):
        continue
    print(i)

Output:

1
3
5
7
9

Example: Checking Prime Number with Break

n = int(input("N: "))

for i in range(2, n):
    if(n % i == 0):
        print("COMPOSITE")
        break
else:
    print("PRIME")

Output:

Enter N: 7
PRIME

Loop Else Clause

The else clause in a loop is executed when the loop completes normally (i.e., not terminated by a break statement).

While Loop with Else

i = 1

while(i <= 10):
    print(i)
    if(i == 5):
        break
    i += 1
else:
    print("ELSE")

Output:

1
2
3
4
5

For Loop with Else

for i in range(1, 6):
    print(i)
    if(i == 3):
        break
else:
    print("ELSE")

Output:

1
2
3

List Comprehension

List comprehension provides a concise way to create lists. It consists of brackets containing an expression followed by a for clause.

Basic List Comprehension

l = [i for i in range(1, 11)]
print('LIST:', l)

Output:

LIST: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example: Filtering with List Comprehension

You can add an if condition to filter items.

numbers = [4, 30, 23, 36, 87, 59, 102, 114, 56, 78, 26]

new_list = [i for i in numbers if i % 2]
print(new_list)

Output:

[23, 87, 59]

Summary

In this chapter, we covered while loops, for loops, nested loops, break and continue statements, the loop else clause, and list comprehensions.

Tasks

  1. Write a program that prints the first 10 natural numbers using a while loop.
  2. Write a program that prints the multiplication table of a given number using a for loop.
  3. Write a program that uses nested loops to print a pattern.
  4. Write a program that demonstrates the use of break and continue statements.
  5. Write a program that uses list comprehension to create a list of squares of the first 10 natural numbers.

Next Chapter: Functions