If Statements in python
Decision-making is a fundamental part of programming. In Python, the statement allows a program to make decisions and execute specific code blocks based on conditions. Whether you're checking a user's age, validating input, or controlling program flow, if statements are essential.
if
What is an if Statement?
An statement evaluates a condition. If the condition is ifTrue, the code inside the if block executes. If the condition is , Python skips that block.
False
Syntax
if condition:
# code to execute
Key Points About if Statements
if- Used for decision-making in programs.
-
Executes code only when a condition is
.True -
Conditions return either
orTrue.False - Indentation is mandatory in Python.
-
Can be combined with
andelsefor multiple conditions.elif -
Supports comparison operators such as:
(equal to)==(not equal to)!=(greater than)>(less than)<(greater than or equal to)>=(less than or equal to)<=
Example 1: Checking Age Eligibility
age = 20
if age >= 18:
print("You are eligible to vote.")
Output
You are eligible to vote.
Explanation
The condition is age >= 18True, so the message is displayed.
Example 2: Checking a Number
number = 5
if number > 0:
print("The number is positive.")
Output
The number is positive.
Explanation
Since 5 is greater than 0, the condition evaluates to True.
Multiple Statements in If Block
You can have multiple statements inside an if block. All statements must be indented at the same level.
Example
age = 20
if age >= 18:
print("You are an adult")
print("You can vote")
print("You have full legal rights")
Common Mistakes to Avoid
-
Forgetting the colon (
:) after the condition. - Incorrect indentation.
-
Using
instead of=for comparisons.== -
Writing conditions that always evaluate to
orTrueunintentionally.False