Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
Python - Variable declarations
Conditional Statements in Python
Loops in Python
Python Functions
Python Classes
OOPS in Python
Python - Hello World Application
Python - import statements
Python - Web API

Conditional Statements in Python



In Python, conditional statements allow you to execute specific blocks of code based on certain conditions. Here are the primary conditional statements used in Python:

1. if Statement

The if statement is the most basic form of conditional statement.

python
age = 18

if age >= 18:
    print("You are an adult.")

2. if..else Statement

The else statement follows an if statement and runs if the if condition is false.

python
age = 16

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

3. if..elif..else Statement

The elif (short for "else if") statement allows you to check multiple conditions.

python
score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D or lower")

4. Nested if Statements

You can nest multiple if statements within each other to check for more complex conditions.

python
num = 10

if num > 0:
    if num % 2 == 0:
        print("The number is positive and even.")
    else:
        print("The number is positive and odd.")
else:
    print("The number is non-positive.")

5. if Statements with Logical Operators

You can combine conditions using logical operators: and, or, and not.

python
x = 5
y = 10

if x > 0 and y > 0:
    print("Both numbers are positive.")

if x > 0 or y > 0:
    print("At least one number is positive.")

if not (x < 0):
    print("x is not negative.")

6. Ternary Conditional Operator

Python also supports a shorthand for if-else using the ternary conditional operator.

python
age = 30
status = "adult" if age >= 18 else "minor"
print(status)  # Outputs: adult

These are the basic conditional statements you can use in Python. If you have any specific scenarios or need further explanations, let me know!




All rights reserved | Privacy Policy | Sitemap