Python Full Tutorial — Part 5

Real programs repeat work. Writing the same code again and again is stupidity. Loops solve this.

What is a Loop?

A loop runs the same block of code multiple times until a condition is met.

The for Loop

for loop is used when you know how many times something should run.

Basic for Loop

for i in range(5):
    print(i)
  

Output:
0 1 2 3 4

Understanding range()

range(start, stop)

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

Starts from 1, stops before 6.

Looping Through Strings

String Loop

name = "Python"

for ch in name:
    print(ch)
  

The while Loop

while loop runs as long as condition is True.

Basic while Loop

count = 1

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

Infinite Loop (Danger)

If condition never becomes False, loop never stops.

Infinite Loop Example

while True:
    print("This will run forever")
  

The break Statement

break stops the loop immediately.

Using break

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

The continue Statement

continue skips current iteration.

Using continue

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

Real-World Example

Password Attempts

attempts = 0

while attempts < 3:
    password = input("Enter password: ")

    if password == "python123":
        print("Access granted")
        break
    else:
        print("Wrong password")

    attempts += 1
  

Common Beginner Mistakes

Key Takeaway

If you understand loops, you understand automation. This is how software scales.

Next part: Data Structures — List, Tuple, Set, Dictionary.

Disclaimer:
This tutorial is for educational purposes only. Practice daily to gain real programming skill.