Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- String Formatting
- Indexing and Slicing
- Set Comprehensions
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Python Core Concepts
Python Collections
- Python collections ChainMap
- Python collections
- Python collections ChainMap<
- Python counters
- Python deque
- Python dictionary
- Python Lists
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Conditional Statements in Python (if
, elif
, else
)
Programming is not just about executing a set of instructions line by line. Often, we need to make decisions within our code — like choosing a path based on user input, checking conditions, or comparing values. That’s where conditional statements come into play.
In Python, conditional statements allow you to make decisions and execute specific blocks of code based on certain conditions. These are the foundation of control flow in any programming language, and Python makes it incredibly intuitive and readable.
Why Are Conditional Statements Important?
Conditional statements are critical because:
- They determine program behavior based on data or user input.
- They allow branching logic — different actions for different conditions.
- They are core to algorithms in software, from calculators to games to data pipelines.
- They help create dynamic, interactive programs.
Whether you’re building a weather app or automating email responses, you’ll need conditional logic to handle various scenarios.
Prerequisites
Before diving into conditional statements, make sure you’re comfortable with:
- Python syntax (indentation, basic structure)
- Variables and data types
- Comparison operators (e.g.,
==
,!=
,>
,<
) - Boolean values (
True
,False
)
What This Guide Covers
- What Are Conditional Statements?
- The
if
Statement - Using
elif
for Multiple Conditions - Adding
else
for Defaults - Logical Operators in Conditions
- Nested Conditional Statements
- Common Mistakes and Pitfalls
- Practical Use Cases
- Best Practices
- Conclusion
1. What Are Conditional Statements?
Conditional statements allow your program to choose different paths based on whether a condition is True
or False
.
Basic Structure:
if condition:
# block of code
elif another_condition:
# another block
else:
# fallback block
Indentation is crucial in Python—it defines blocks of code.
2. The if
Statement
The simplest form of a conditional statement.
Example:
x = 10
if x > 5:
print("x is greater than 5")
If the condition inside the if
evaluates to True
, the code block runs. If not, it’s skipped.
3. Using elif
for Multiple Conditions
Use elif
(short for else if) to check multiple conditions in sequence.
Example:
x = 10
if x < 5:
print("x is less than 5")
elif x == 10:
print("x is exactly 10")
elif x > 10:
print("x is greater than 10")
Only the first True
condition block executes. Others are ignored.
4. Adding else
for Default Cases
Use else
when none of the if
or elif
conditions match.
Example:
x = 7
if x < 5:
print("Less than 5")
elif x == 10:
print("Equal to 10")
else:
print("Something else") # This will print
The else
block must come last.
5. Logical Operators in Conditions
You can combine multiple conditions using logical operators:
and
– All conditions must beTrue
or
– At least one condition must beTrue
not
– Inverts the condition
Example:
x = 7
if x > 5 and x < 10:
print("x is between 5 and 10") # True
Another:
if not x == 10:
print("x is not 10")
6. Nested Conditional Statements
You can place if
statements inside other if
statements for more complex logic.
Example:
x = 20
if x > 10:
if x < 30:
print("x is between 10 and 30")
While powerful, avoid deep nesting to keep your code readable.
7. Common Mistakes and Pitfalls
- Missing Indentation: Python uses indentation to group code blocks.
if x > 5: print("Wrong indentation") # Will raise an error
- Using
=
Instead of==
:if x = 5: # Wrong, this is an assignment
- Using too many
elif
statements when amatch
(Python 3.10+) is better. - Logical errors in combined conditions.
8. Practical Use Cases
1. User Authentication
username = input("Enter username: ")
if username == "admin":
print("Access granted")
else:
print("Access denied")
2. Grade Calculator
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C or below")
3. Number Checker
num = -5
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
4. Time of Day
hour = 15
if hour < 12:
print("Good morning")
elif hour < 18:
print("Good afternoon")
else:
print("Good evening")
5. Shipping Calculator
weight = 2.5
if weight < 1:
cost = 5
elif weight < 3:
cost = 10
else:
cost = 15
print(f"Shipping cost: ${cost}")
9. Best Practices
- Use meaningful condition checks. Avoid cryptic conditions.
- Limit nested
if
statements. Use logical operators instead. - Comment tricky conditions.
- Test edge cases (e.g.,
x == 0
, negative numbers). - Be consistent with spacing and indentation.
Conditional statements in Python — using if
, elif
, and else
— form the backbone of decision-making in programs. Whether it’s handling user input, evaluating data, or guiding your app’s behavior, these tools are essential.
By understanding how to use them properly and following best practices, you can write clean, efficient, and readable code. As you advance in your Python journey, you’ll see just how often these simple statements become building blocks for more complex logic.