Python Tutorial (5) If, elif & else Condition
What is IF condition in python with Example?
In Python, the if statement is used for conditional execution of code. It allows you to execute a block of code only if a specified condition is true. Here’s the basic syntax of an if statement:
if condition:
# Code to be executed if the condition is true
The indented block of code under the if statement is executed only when the specified condition is true. If the condition is false, the block of code is skipped.
Let’s look at some examples:
Example 1: Simple if Statement
# Example 1: Simple if statement
x = 10
if x > 5:
print(“x is greater than 5”)
In this example, the print statement is executed because the condition x > 5 is true.
Example 2: if-else Statement
# Example 2: if-else statement
y = 3
if y % 2 == 0:
print(“y is even”)
else:
print(“y is odd”)
This example uses an if-else statement to check if y is even or odd. If the condition y % 2 == 0 is true, the first block of code is executed; otherwise, the block under else is executed.
Example 3: if-elif-else Statement
# Example 3: if-elif-else statement
grade = 75
if grade >= 90:
print(“A”)
elif grade >= 80:
print(“B”)
elif grade >= 70:
print(“C”)
else:
print(“F”)
This example checks the value of grade and prints the corresponding letter grade. The elif (short for “else if”) allows you to check multiple conditions in sequence.
Example 4: Nested if Statements
# Example 4: Nested if statements
num = 15
if num > 0:
if num % 2 == 0:
print(“Positive and even”)
else:
print(“Positive and odd”)
elif num < 0:
print(“Negative”)
else:
print(“Zero”)
Here, the if statements are nested. The inner if-else statement is only evaluated if the outer condition is true.
Example 5: Short if Statement (Ternary Operator)
# Example 5: Short if statement (ternary operator)
a = 10
b = 20
max_value = a if a > b else b
print(“Maximum value:”, max_value)
This example uses the ternary operator to find the maximum value between a and b in a concise way.
if statements are fundamental to control the flow of a Python program based on conditions. They allow you to make decisions in your code, executing different blocks based on the evaluation of specific conditions.
What is else condition in python with Example?
In Python, the else statement is used in conjunction with an if statement to specify a block of code that should be executed when the if condition is false. The basic syntax is as follows:
if condition:
# Code to be executed if the condition is true
else:
# Code to be executed if the condition is false
# Example: Using else with if statement
x = 5
if x > 10:
print(“x is greater than 10”)
else:
print(“x is not greater than 10”)
In this example, the if statement checks if the value of x is greater than 10. If the condition is true, the code inside the if block is executed. Otherwise, the code inside the else block is executed. In this case, since x is 5 (which is not greater than 10), the output will be “x is not greater than 10.”
Example with elif:
# Example: Using else with if-elif statements
score = 75
if score >= 90:
print(“A”)
elif score >= 80:
print(“B”)
elif score >= 70:
print(“C”)
else:
print(“F”)
In this example, the else statement is used in conjunction with if-elif statements to provide a default case. If none of the preceding conditions (score >= 90, score >= 80, score >= 70) is true, the block of code under else will be executed, and “F” will be printed.
The else statement is a powerful tool for handling different cases and providing fallback actions when a specific condition is not met. It allows your program to gracefully handle scenarios where the primary condition is false, offering an alternative course of action.
What is elif condition in python with Example?
In Python, the elif statement (short for “else if”) is used to introduce additional conditions after an initial if statement. It allows you to check multiple conditions sequentially and execute the code block associated with the first true condition. The basic syntax looks like this:
if condition1:
# Code to be executed if condition1 is true
elif condition2:
# Code to be executed if condition2 is true
elif condition3:
# Code to be executed if condition3 is true
# …
else:
# Code to be executed if none of the conditions is true
Here’s an example to illustrate the use of elif:
# Example: Using elif with if statements
x = 15
if x > 10:
print(“x is greater than 10”)
elif x > 5:
print(“x is greater than 5 but not greater than 10”)
else:
print(“x is 5 or less”)
In this example, the if statement checks if x is greater than 10. If that condition is true, the corresponding block of code is executed. If the initial condition is false, the elif statement is evaluated. If x is greater than 5 but not greater than 10, the code block under elif is executed. If both conditions (x > 10 and x > 5) are false, the code block under else is executed.
Example with Multiple Elif Statements:
# Example: Using multiple elif statements
day = “Wednesday”
if day == “Monday”:
print(“Start of the week”)
elif day == “Wednesday”:
print(“Midweek”)
elif day == “Friday”:
print(“End of the week”)
else:
print(“Some other day”)
In this example, the elif statements are used to check the day of the week. The code block under the first true condition will be executed. If no conditions are true, the code block under else will be executed.
The elif statement is particularly useful when you have multiple conditions to check, and you want to handle each case differently. It helps to structure your code in a way that makes it clear and readable, especially when dealing with complex branching logic.
Why we need use If , else and elif condition in python with Example?
Conditional statements in Python, including if, else, and elif, are essential for controlling the flow of a program based on certain conditions. They allow you to make decisions and execute specific blocks of code depending on whether certain conditions are true or false. Here are some reasons why you might need to use these conditional statements, along with examples:
Decision Making:
# Example: Decision making using if-else
age = 18
if age >= 18:
print(“You are eligible to vote.”)
else:
print(“You are not eligible to vote.”)
Conditional statements are crucial for making decisions in your program. In this example, the code checks if the age is greater than or equal to 18 and prints a message accordingly.
Handling Multiple Conditions:
# Example: Handling multiple conditions with if-elif-else
score = 75
if score >= 90:
print(“A”)
elif score >= 80:
print(“B”)
elif score >= 70:
print(“C”)
else:
print(“F”)
elif (else if) allows you to check multiple conditions sequentially. In this example, the code determines the letter grade based on the value of score.
Error Handling:
# Example: Basic error handling using if-else
user_input = input(“Enter a number: “)
if user_input.isdigit():
number = int(user_input)
print(f”Square of {number}: {number**2}”)
else:
print(“Invalid input. Please enter a number.”)
Conditional statements can be used for basic error handling. Here, the code checks if the user input is a digit before performing further operations.
Ternary Operator for Conciseness:
# Example: Ternary operator for concise conditional expression
a = 10
b = 20
max_value = a if a > b else b
print(“Maximum value:”, max_value)
The ternary operator (a if condition else b) provides a concise way to express a conditional statement. In this example, it determines the maximum value between a and b.
Loop Control:
# Example: Using if-else for loop control
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
print(f”{num} is even”)
else:
print(f”{num} is odd”)
Conditional statements can be used within loops to control the flow of the loop based on certain conditions. Here, the code identifies whether each number in the list is even or odd.
Conditional statements are fundamental to programming and are used to create flexible and responsive code. They enable you to handle different scenarios, validate input, and execute specific actions based on the current state of your program.
What is for loops in python with Example?
In Python, a for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each element in that sequence. The basic syntax of a for loop is as follows:
for variable in sequence:
# Code to be executed for each element in the sequence
Here’s an example to illustrate the use of a for loop:
Example 1: Iterate Over a List
# Example 1: Iterate over a list
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
In this example, the for loop iterates over each element in the list fruits, and the variable fruit takes on each value in the sequence one by one. The output will be:
apple
banana
cherry
Example 2: Iterate Over a Range of Numbers
# Example 2: Iterate over a range of numbers
for i in range(1, 5):
print(i)
The range(1, 5) generates a sequence of numbers from 1 to 4, and the for loop iterates over these numbers, printing each one. The output will be:
1
2
3
4
Example 3: Iterate Over Characters in a String
# Example 3: Iterate over characters in a string
message = “Python”
for char in message:
print(char)
This example uses a for loop to iterate over each character in the string “Python” and prints each character. The output will be:
P
y
t
h
o
n
Example 4: Iterate Over a Dictionary
# Example 4: Iterate over dictionary keys and values
person = {“name”: “John”, “age”: 30, “city”: “New York”}
for key, value in person.items():
print(f”{key}: {value}”)
In this example, the for loop iterates over the key-value pairs in the dictionary person. The output will be:
name: John
age: 30
city: New York
Example 5: Nested For Loop
# Example 5: Nested for loop to create a multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end=’\t’)
print() # Move to the next line after each row
This example demonstrates a nested for loop to create a multiplication table. The outer loop iterates over the rows, and the inner loop iterates over the columns. The end=’\t’ argument in the print statement is used to print the values with a tab separator. The output will be:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
for loops are powerful constructs for handling iterations in Python, making it convenient to process each element in a sequence or perform repetitive tasks. They enhance code readability and reduce the need for duplicated code.
Why we need use for loops in python with Example?
for loops in Python are essential for situations where you need to iterate over a sequence of elements and perform a specific operation for each element. Here are some reasons why you might need to use for loops, along with examples:
Iterating Over Lists, Tuples, or Strings:
# Example 1: Iterate over a list
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
This is a common use case where you want to perform an operation for each element in a list. In this example, the loop iterates over each fruit in the list and prints it.
Generating Sequences of Numbers:
# Example 2: Generate a sequence of numbers
for i in range(1, 6):
print(i)
The range() function combined with a for loop is often used to generate a sequence of numbers. In this example, it prints numbers from 1 to 5.
Working with Strings:
# Example 3: Iterate over characters in a string
message = “Hello, Python!”
for char in message:
print(char)
for loops simplify the process of iterating over the characters of a string or the elements of any iterable.
Iterating Over Dictionaries:
# Example 4: Iterate over dictionary keys and values
person = {“name”: “John”, “age”: 30, “city”: “New York”}
for key, value in person.items():
print(f”{key}: {value}”)
for loops are useful for iterating over key-value pairs in dictionaries.
Nested Loops for Multi-dimensional Data:
# Example 5: Nested for loop for a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=’ ‘)
print()
Nested for loops are handy when working with multi-dimensional data structures like matrices.
Repeating a Task a Specific Number of Times:
# Example 6: Repeat a task a specific number of times
for i in range(3):
print(“Hello, Python!”)
If you need to repeat a task a certain number of times, a for loop with range() is a concise way to achieve that.
for loops are versatile and provide a clean and readable way to handle iterations. They are fundamental for processing sequences and collections of data in a concise manner, making your code more efficient and expressive.