Skip to content

Latest commit

 

History

History
250 lines (165 loc) · 2.64 KB

File metadata and controls

250 lines (165 loc) · 2.64 KB

Loops in Python

(for Loop and while Loop)


1. Introduction

Sometimes we need to repeat a task multiple times.

Examples:

  • Print numbers from 1 to 10
  • Print a message 5 times
  • Check numbers one by one
  • Process multiple inputs

Instead of writing the same code again and again, we use loops.

Loops allow us to execute a block of code repeatedly.

There are two main loops in Python:

  1. for loop
  2. while loop

2. The for Loop

The for loop is mainly used when we know how many times we want to repeat something.


Using range()

range() is commonly used with for loop.

Example 1: Print 1 to 5

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

Output:

1
2
3
4
5

Important:

  • Start value is included
  • End value is excluded

Different Forms of range()

  1. range(stop)
for i in range(5):
    print(i)

Output:

0
1
2
3
4
  1. range(start, stop)
for i in range(2, 6):
    print(i)
  1. range(start, stop, step)
for i in range(1, 10, 2):
    print(i)

Output:

1
3
5
7
9

Looping Through a String

text = "Python"

for ch in text:
    print(ch)

This prints each character one by one.


3. The while Loop

The while loop runs as long as the condition is True.

Syntax:

while condition:
    statement

Example: Print 1 to 5

i = 1

while i <= 5:
    print(i)
    i += 1

Important:

  • Always update the variable inside the loop
  • Otherwise, it becomes an infinite loop

Infinite Loop Example (Wrong)

i = 1

while i <= 5:
    print(i)

This will run forever because i never changes.


4. Loop Control Statements


break

Stops the loop completely.

for i in range(1, 10):
    if i == 5:
        break
    print(i)

Output:

1
2
3
4

continue

Skips the current iteration.

for i in range(1, 6):
    if i == 3:
        continue
    print(i)

Output:

1
2
4
5

5. Difference Between for and while

Use for loop when:

  • Number of repetitions is known

Use while loop when:

  • Repetition depends on a condition

6. Common Beginner Mistakes

  1. Forgetting to update variable in while loop
  2. Wrong indentation
  3. Using incorrect range values
  4. Creating accidental infinite loops

7. Practice Exercises

  1. Print numbers from 1 to 20
  2. Print even numbers from 1 to 20
  3. Print multiplication table of a number
  4. Count from 10 down to 1
  5. Print each character of a word

Example:

num = int(input("Enter number: "))

for i in range(1, 11):
    print(num * i)