In real-life situations, we often make decisions and repeat tasks based on certain conditions. Similarly In programming, conditional and iterative statements control the flow of execution based on conditions or repetition. Python provides simple and readable syntax to manage both.
In Python, conditional statements are used to execute certain blocks of code only if a specified condition is true.
1. if statement in Python
2. if-else statement in Python
3. if-elif-else statement in Python
4. Nested if-else statement in Python
5. Short Hand if statement in Python
6. Short Hand if-else statement in Python
The if statement in Python is used to execute a block of code only if a specified condition is true.
age = 18
if age >= 18:
print("You are eligible to vote.")
The if-else statement in Python is used to execute one block of code if a condition is true, and another block if the condition is false.
marks = 75
if marks >= 50:
print("You passed the exam.")
else:
print("You failed the exam.")
The if-elif-else statement in Python is used to check multiple conditions. It executes the block of code for the first true condition, and if none are true, the else block runs.
marks = 68
if marks >= 85:
print("Grade: S")
elif marks >= 75:
print("Grade: A")
elif marks >= 65:
print("Grade: B")
elif marks >= 55:
print("Grade: C")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: F")
A nested if-else statement in Python means using an if-else condition inside another if or else block. It helps to check multiple conditions in a structured way.
age = 20
citizenship = "Indian"
if age >= 18:
if citizenship == "Indian":
print("You are eligible to vote.")
else:
print("You are not an Indian citizen.")
else:
print("You are too young to vote.")
A short hand if statement in Python allows you to write an if statement in a single line.
If you have only one statement to execute, you can put it on the same line as the if statement.
x = 5
print("Positive number") if x > 0 else None
if a > b: print("a is greater than b")
A short hand if-else statement in Python allows you to write both the if and else conditions in a single line, making the code more concise and readable.
value_if_true if condition else value_if_false
This technique is known as Ternary Operators, or Conditional Expressions.
num = 7
result = "Even" if num % 2 == 0 else "Odd"
print("The number is", result)
num = 0
result = "Positive" if num > 0 else "Negative" if num < 0 else "Zero"
print("The number is", result)
Iterative statements in Python, also known as loops, are used to repeat a block of code multiple times as long as a given condition is true.
Python provides two main types of loops:
1. while loop Statement in Python
2. for loop Statement in Python
With the while loop we can execute a set of statements as long as a given condition is true.
count = 1
while count <= 5:
print("Count is:", count)
count += 1
A for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
range(start, stop, step) – Three Arguments
| Argument Name | Description | Default | Example | Output |
|---|---|---|---|---|
| start | Starting value of the sequence | 0 | range(2, 6) |
2, 3, 4, 5 |
| stop | End value (not included) | Required | range(5) |
0, 1, 2, 3, 4 |
| step | Difference between numbers | 1 | range(1, 10, 2) |
1, 3, 5, 7, 9 |
for i in range(5):
print(i)
for i in range(2, 6):
print(i)
for i in range(1, 10, 2):
print(i)
for i in range(5, 0, -1):
print(i)
A nested loop is a loop inside a loop.
The inner loop runs completely every time the outer loop runs once. It is useful for tasks like printing patterns, working with rows and columns, or handling multi-dimensional data.
for i in range(1, 4):
print("Outer Loop",i)
for j in range(1, 3):
print("Inner Loop",j)
Jump statements are used to change the normal flow of execution inside loops in Python.
These statements help control how and when a loop should terminate or skip specific iterations.
Python supports the following jump statements:
1. break statement in Python
2. continue statement in Python
3. pass statement in Python
With the break statement, you can stop a loop at any point, even if the loop's condition is still true. Works with both for and while loops.
for i in range(1, 10):
if i == 5:
break # Exit the loop when i equals 5
print(i)
With the break statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry", "mango"]
for fruit in fruits:
if fruit == "cherry":
print("Found cherry! Exiting loop.")
break # Exit the loop when cherry is found
print(fruit)
The continue statement is used to skip the current iteration of the loop and moves to the next iteration, without exiting the loop entirely.
i = 0
while i < 5:
i += 1
if i == 3:
continue # Skip printing 3
print(i)
continue keyword skips the current iteration of the for loop and moves to the next iteration
numbers = [10, -5, 3, -2, 8, -1, 0, 7]
for number in numbers:
if number <= 0:
continue # Skip non-positive numbers
print("Positive number: ", number)
The pass statement in Python is a null operation that is used when a statement is required syntactically but you do not want to execute any code.
numbers = [10, -5, 3, -2, 8, -1, 0, 7]
for number in numbers:
if number <= 0:
pass # Do nothing for non-positive numbers
else:
print("Positive number: ", number)
The else block is executed when the loop condition becomes false, and the loop has iterated completely without being interrupted by break.
If a break statement is encountered, the else block will not run.
# Example: Checking if all elements in a list are positive
numbers = [10, 20, 30, 40, 50]
index = 0
while index < len(numbers):
if numbers[index] < 0:
print("Negative number found:", numbers[index])
break
index += 1
else:
print("All numbers are positive.")
In Python, the else clause with a for loop is executed after the loop completes all its iterations without encountering a break statement. If the loop is terminated by a break, the else block will not run.
# Example: Searching for a specific number in a list
numbers = [5, 10, 15, 20, 25]
search_number = 15
for number in numbers:
if number == search_number:
print("Found the number:", search_number)
break
else:
print("Number not found.")
It tests if a condition is true, and if it is not true, it raises an AssertionError with an optional message. This is useful when you want to ensure that certain conditions hold true during the execution of the program.
balance = 5000 # Current bank balance
# Take the withdrawal amount as input from the user
withdrawal_amount = float(input("Enter the amount to withdraw: "))
# Assert that the withdrawal amount is not more than the available balance
assert withdrawal_amount <= balance, "Insufficient balance for this withdrawal!"
# Perform the withdrawal
balance -= withdrawal_amount
print("Withdrawal successful! New balance:", balance)
When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
The try block lets you test a block of code for errors.
The except block lets you handle the error.
try:
print(x)
except:
print("An exception occurred")
You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
The else block lets you execute code when there is no error.
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
The finally block lets you execute code, regardless of the result of the try- and except blocks.
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")