Web Development
HTML Course
CSS Course
JavaScript Course
PHP Course
Python Course
SQL Course
SEO Course

Control Structures

if-elif-else Statements in Python

Conditional statements allow code execution based on certain conditions. Python uses if, elif (else if), and else to control the program flow.

Example - simple condition

x = 10

if x > 5:
    print("x is greater than 5")  # Executes if the condition is True

Example - condition with elif and else

grade = 7

if grade >= 9:
    print("Excellent")         # grade โ‰ฅ 9
elif grade >= 7:
    print("Very good")         # grade โ‰ฅ 7 but < 9
else:
    print("Keep practicing")   # grade < 7
Note:
  • Indentation (spaces at the beginning of the line) is mandatory in if blocks.
  • You can have any number of elif, but only one else.
  • Conditions are evaluated top-down - it stops at the first that is True.

for Loop in Python

The for loop is used to repeat an action a known number of times. You can iterate through lists, strings, sets, dictionaries, or any iterable object.

Example - iterating through a list

fruits = ["apples", "pears", "bananas"]

for fruit in fruits:
    print(fruit)   # Displays each element in the list

Example - iterating through a string

text = "Python"

for letter in text:
    print(letter)   # Displays each character in the string

Example - using range()

for i in range(5):
    print(i)   # Displays: 0, 1, 2, 3, 4
Note:
  • range(n) generates a sequence from 0 to n-1.
  • You can specify the start and step: range(1, 10, 2) โ†’ 1, 3, 5, 7, 9.
  • The for loop is ideal when you know how many iterations you want to perform.

while Loop and range() Function in Python

The while loop executes a block of code as long as a condition is true. It is ideal when you don't know in advance how many iterations are needed. The range() function is often used with a for loop, but you can also combine it with while if you want to manually control the index.

Example - simple while loop

i = 0

while i < 5:
    print(i)   # Displays: 0, 1, 2, 3, 4
    i += 1     # Increases the value of i each step

Example - using range() with for

for number in range(1, 6):
    print(number)   # Displays: 1, 2, 3, 4, 5

Example - range() with custom step

for x in range(0, 10, 2):
    print(x)   # Displays: 0, 2, 4, 6, 8
Note:
  • The while loop can become infinite if you do not change the condition.
  • range(start, stop, step) is flexible and efficient for controlling sequences.
  • Use for when you know how many steps you have, and while when the condition is dynamic.

break, continue and pass Statements in Python

These special statements control loop behavior. They are useful for stopping, skipping, or ignoring an iteration during execution.

break Statement

Completely stops the current loop.

for i in range(10):
    if i == 5:
        break           # Stops the loop when i reaches 5
    print(i)            # Displays: 0, 1, 2, 3, 4

continue Statement

Skips the current iteration and moves to the next one.

for i in range(5):
    if i == 2:
        continue        # Skips 2
    print(i)            # Displays: 0, 1, 3, 4

pass Statement

Does nothing - serves as a placeholder for an empty code block.

x = 10

if x > 5:
    pass               # Nothing happens here

print("Continuing...")  # Code continues normally
Note:
  • break is useful for exiting loops based on a condition.
  • continue helps you ignore special cases without stopping the loop.
  • pass is used when you need a valid syntactic structure but don't want to write code there (e.g., in an unimplemented function).

Ternary Operator in Python

The ternary operator is a compact form of if-else that returns a value based on a condition. It is useful for short and clear expressions.

Syntax

value = x if condition else y

Example - simple check

age = 18
message = "Adult" if age >= 18 else "Minor"
print(message)   # Displays: Adult

Example - applied in a function

def parity(n):
    return "even" if n % 2 == 0 else "odd"

print(parity(7))   # Displays: odd
print(parity(10))  # Displays: even
Note:
  • The ternary operator is ideal for quick assignments based on conditions.
  • Not recommended for complex expressions - use classic if-else for clarity.
  • You can use the ternary operator directly in return, print, or assignments.

๐Ÿง  Quiz - Control Structures in Python

Top