No Widget Added

Please add some widget in Offcanvs Sidebar

Shopping cart

shape
shape

Python If-else statements

Python if else statement

In Python, if-else statements are used to execute code based on certain conditions. These conditional statements allow you to control the flow of your program. The basic structure includes if, elif (short for else if), and else.

Basic Structure

  1. if statement: This executes a block of code if its condition is true.
  2. elif statement: This stands for “else if” and allows you to check multiple expressions for true and execute a block of code as soon as one of the conditions is true.
  3. else statement: This executes a block of code if all preceding conditions are false.

Syntax

if condition1:
    # block of code to be executed if condition1 is true
elif condition2:
    # block of code to be executed if condition2 is true
else:
    # block of code to be executed if all conditions are false

Examples

Example 1: Basic if-else

x = 10

if x > 0:
    print("x is positive")
else:
    print("x is non-positive")

Output:

x is positive

Example 2: if-elif-else

x = 0

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

Output

x is zero

Example 3: Nested if-else

x = 15

if x > 10:
    if x > 20:
        print("x is greater than 20")
    else:
        print("x is between 10 and 20")
else:
    print("x is 10 or less")

Output

x is between 10 and 20

Example 4: Checking multiple conditions

x = 25

if x % 2 == 0:
    print("x is even")
else:
    print("x is odd")

if x % 5 == 0:
    print("x is a multiple of 5")
else:
    print("x is not a multiple of 5")

Output

x is odd
x is a multiple of 5

Combining Conditions with Logical Operators

You can use logical operators (and, or, not) to combine multiple conditions in an if statement.

Example 5: Combining conditions

x = 30

if x > 0 and x % 2 == 0:
    print("x is a positive even number")
else:
    print("x is either negative or odd")

Output

x is a positive even number

Using If-Else in a Function

Example 6: If-else in a function

def check_number(num):
    if num > 0:
        return "Positive"
    elif num == 0:
        return "Zero"
    else:
        return "Negative"

result = check_number(-5)
print(result)  # Output: Negative

Summary

  • if statement: Executes a block of code if its condition is true.
  • elif statement: Checks another condition if the previous conditions are false.
  • else statement: Executes a block of code if all preceding conditions are false.
  • Nested if-else: You can nest if-else statements inside each other.
  • Combining conditions: Use logical operators (and, or, not) to combine multiple conditions.

Leave A Comment

Your email address will not be published. Required fields are marked *