Python Conditional Statement

0 0
Read Time:1 Minute, 13 Second

Conditional Statements:

Conditional statements are used to perform different actions based on different conditions.

1. if Statement:

Syntax:

if condition:
 # Code block to execute if condition is True

Example:

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

2. if-else Statement:

Syntax:

if condition:
 # Code block to execute if condition is True
else:
 # Code block to execute if condition is False

Example:

age = 18
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")

3. if-elif-else Statement:

Syntax:

if condition1:
    # Code block to execute if condition1 is True
elif condition2:
    # Code block to execute if condition2 is True
else:
    # Code block to execute if both condition1 and condition2 are False

Example:

num = 0
if num > 0:
    print("Positive number")
elif num < 0:
    print("Negative number")
else:
    print("Zero")

4. Nested if Statements:

You can have an if statement inside another if statement.

Example:

num = 10
if num > 0:
    if num % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")
else:
    print("Number is not positive")

5. Ternary Operator:

A concise way to write if-else statements in a single line.

Syntax:

value_if_true if condition else value_if_false

Example:

x = 10
is_even = True if x % 2 == 0 else False
print(is_even)

Remember:

  • Indentation is crucial in Python. Use consistent indentation (usually four spaces) to define code blocks within conditional statements.
  • Conditions are generally expressions that evaluate to True or False.
Happy
Happy
100 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Verified by MonsterInsights