What is an if Statement?
The if statement is used to execute a block of code only when a specified
condition is true.
If the condition is false, the block is skipped and the program continues normally.
Syntax:
if condition:
# code to execute if condition is True
Example 1 (Condition True):
age = 18
if age >= 18:
print("You are eligible to vote.")
Output:
You are eligible to vote.
Explanation:
- Here, age is 18.
- The
ifcondition checks if age is 18 or more. - Since it is true, the message "You are eligible to vote." is printed.
Example 2 (Condition False):
marks = 30
if marks >= 40:
print("You passed!")
Output:
(No output, as the condition is False)
Explanation:
- Here, the value of
marksis 30. - The
ifstatement checks if marks are greater than or equal to 40. - Since 30 is less than 40, the condition is false.
- Because the condition is false, the print statement does not run.
- So, nothing is printed on the screen.
Important Notes:
- Indentation is required in Python (usually 4 spaces).
- Conditions are usually written using comparison operators.
- If the condition is
False, the block is ignored.