if Statements
The if
statement in Python allows you to check multiple conditions and execute different blocks of code based on the first condition that evaluates to true.
Syntax
The syntax of an if
statement in Python is:
if condition_1:
statement_block_1 ## Every Block in Python is Indented
elif condition_2:
statement_block_2
else:
statement_block_3
Note: Before learning about the if
statement, you should have a basic understanding of indentation in Python. Indentation is crucial for structuring code blocks. Unlike other languages that use braces {}
to delineate blocks, Python relies on indentation. Let's explore the fundamentals of Python indentation, its significance, and how it's applied.
Example
- In this example, the if statement checks if the variable
x
is greater than zero. If the condition is true, the statement print("x is positive")
is executed.
## Example: Check if a number is positive
>>> x = 10
>>> if x > 0:
... print("x is positive")
...
x is positive
Tips: You need type four spaces before the print statement to make it part of the if block. Typing the Enter key at the end of the line will execute the block.
- In this example, the if-else statement checks if the variable
x
is greater than zero. If the condition is true, the statement print("x is positive")
is executed; otherwise, the statement print("x is negative")
is executed.
## Example: Check if a number is positive or negative
>>> x = -5
>>>
>>> if x > 0:
... print("x is positive")
... else:
... print("x is negative")
...
x is negative
- In this example, the if-elif-else statement checks the value of the variable marks and prints the corresponding grade based on the conditions provided. Since marks is 75, the condition
marks >= 70
evaluates to true, so the statement print("Grade: C")
is executed.
## Example: Determine the grade based on marks
>>> marks = 75
>>>
>>> if marks >= 90:
... print("Grade: A")
... elif marks >= 80:
... print("Grade: B")
... elif marks >= 70:
... print("Grade: C")
... else:
... print("Grade: Fail")
...
Grade: C
The if statement provides a flexible way to control the flow of your program based on different conditions. It's a fundamental building block for writing conditional logic in Python.