Python Control Structures: Mastering Conditional Statements and Loops

Python control structures are blocks of code that decide the flow of execution based on certain conditions and loops. They are the building blocks of a Python program and are used for decision making and repeating tasks. This guide will help you master conditional statements and loops in Python with examples.

Conditional Statements

If Statement

The if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

x = 10
if x > 0:
    print("x is positive")

If-Else Statement

The if-else statement provides an alternative choice when an if clause evaluates to False. The else clause is executed if the condition in the if statement is False.

x = -10
if x > 0:
    print("x is positive")
else:
    print("x is negative")

Elif Statement

The elif statement allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.

x = 0
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

Loops

Loops in Python are used to repeatedly execute a block of statements until a certain condition is met.

For Loop

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects. Iterating over a sequence is called traversal.

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

While Loop

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.

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

The break statement terminates the loop statement and transfers execution to the statement immediately following the loop.

for letter in 'Python':
   if letter == 'h':
      break
   print('Current Letter :', letter)

Continue Statement

The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

for letter in 'Python':
   if letter == 'h':
      continue
   print('Current Letter :', letter)

Pass Statement

The pass statement is a null operation; nothing happens when it executes. Python pass is often used for creating minimal classes or functions.

for letter in 'Python': 
   if letter == 'h':
      pass
      print('This is pass block')
   print('Current Letter :', letter)


Python Basics Home Page [TOC]                             Python Basics                          Python Functions and Modules

You may also like...

Leave a Reply