Wednesday, February 25, 2026

Python Conditionals and Loops

 

Python Conditionals and Loops

Python is a versatile programming language that emphasizes readability and simplicity. Two of its most fundamental features are conditionals and loops, which allow developers to control the flow of execution in their programs.


🌍 Conditionals in Python

Conditionals are used to make decisions in code. They evaluate expressions and execute blocks of code depending on whether the condition is True or False.

If Statement

x = 10
if x > 5:
    print("x is greater than 5")

If-Else Statement

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

Elif Statement

x = 7
if x > 10:
    print("x is greater than 10")
elif x > 5:
    print("x is greater than 5 but less than or equal to 10")
else:
    print("x is less than or equal to 5")

🔄 Loops in Python

Loops allow repetitive execution of code blocks until a condition is met.

For Loop

Used to iterate over sequences like lists, tuples, strings, or ranges.

for i in range(5):
    print("Iteration:", i)

While Loop

Executes as long as a condition remains True.

count = 0
while count < 5:
    print("Count:", count)
    count += 1

⚡ Loop Control Statements

  • Break: Exits the loop immediately.
for i in range(10):
    if i == 5:
        break
    print(i)
  • Continue: Skips the current iteration and moves to the next.
for i in range(5):
    if i == 2:
        continue
    print(i)
  • Else with Loops: Executes after the loop finishes normally (without break).
for i in range(3):
    print(i)
else:
    print("Loop completed without break")

✨ Practical Example

numbers = [1, 2, 3, 4, 5, 6]

for num in numbers:
    if num % 2 == 0:
        print(num, "is even")
    else:
        print(num, "is odd")

This combines conditionals and loops to classify numbers as even or odd.


📖 Conclusion

Conditionals and loops are the core control structures in Python. Conditionals allow branching logic, while loops enable repetition. Together, they make programs dynamic, flexible, and capable of handling complex tasks.

No comments:

Post a Comment

Support Vector Machines in Machine Learning

Support Vector Machines in Machine Learning Introduction Support Vector Machines (SVMs) are powerful supervised learning algorithms used ...