Python Full Tutorial — Part 4: If-Else & Decision Making

By Suraj Ahir December 13, 2025 6 min read

Python — Python Functions
Python — Python Functions
← Part 3 Python Tutorial · Part 4 of 12 Part 5 →

Until now, your Python programs ran every line from top to bottom without skipping anything. Real programs are smarter — they take different paths based on conditions. This is decision making, and it is one of the most important concepts in all of programming.

What is an if Statement?

An if statement checks a condition. If that condition is True, Python runs the code inside it. If it is False, Python skips it.

Basic if Statement
age = 20
if age >= 18:
    print("You are an adult.")
    print("You can vote.")

Notice the colon after the condition and the indentation of the code block. Indentation is not optional in Python — it is how Python knows which lines belong to the if block. Use 4 spaces consistently.

if-else

When you want to handle both outcomes — condition True AND condition False:

if-else Example
marks = 45
if marks >= 50:
    print("You passed!")
else:
    print("You need to study more.")

elif — Multiple Conditions

When you have more than two possible outcomes, use elif (else if):

elif Chain
score = 78
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"
print(f"Your grade is: {grade}")

Python checks each condition from top to bottom. As soon as one is True, it runs that block and skips all the rest. Order matters.

Nested if Statements

You can put if statements inside other if statements for multi-level decisions:

Nested if
has_ticket = True
age = 16
if has_ticket:
    if age >= 18:
        print("Entry allowed")
    else:
        print("Need parent permission")
else:
    print("No ticket, no entry")

Combining Conditions with and/or

Combined Conditions
username = "admin"
password = "secure123"
if username == "admin" and password == "secure123":
    print("Login successful")
else:
    print("Wrong credentials")

Practical Project — BMI Calculator

BMI Calculator
weight = float(input("Weight in kg: "))
height = float(input("Height in meters: "))
bmi = weight / (height ** 2)
print(f"Your BMI: {bmi:.1f}")
if bmi < 18.5:
    print("Underweight — Eat more nutritious food")
elif bmi < 25:
    print("Normal weight — Keep it up!")
elif bmi < 30:
    print("Overweight — Add exercise to routine")
else:
    print("Obese — Consult a doctor for guidance")

The Ternary (Inline) if

For simple conditions, Python has a compact one-line syntax:

Ternary Operator
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)  # Adult

Common Mistake — == vs =

One of the most common beginner errors: using = (assignment) instead of == (comparison) inside an if condition. Always use == when comparing values in conditions.

In Part 5, we will learn loops — how Python repeats actions, which is where programs start handling real-world data at scale.

Common Mistakes Beginners Make

Learning from common pitfalls saves hours of frustration. Here are the mistakes most beginners make in this area and how to avoid them.

The first mistake is trying to memorize syntax before understanding logic. Python syntax is simple — you could memorize it in a day. But if you do not understand why you are writing what you are writing, you will not be able to adapt when things change or when a problem looks slightly different. Always ask: what problem does this solve?

The second mistake is writing very long functions or very long scripts without breaking them into logical units. Real professional code is made of small, focused pieces that each do one thing well. The moment your code does two or three unrelated things in one block, it is time to split it up.

The third mistake is not reading error messages. Python's error messages are actually quite good. They tell you the file, the line number, the type of error, and often a description. Read the entire error before searching online. The answer is usually right there.

How This Topic Appears in Real Projects

In real codebases, every concept from this tutorial series appears constantly. Backend web applications built with Flask or Django use functions, classes, data structures, and error handling throughout every route and service. Data pipelines use loops and comprehensions to process thousands of records efficiently. CLI tools use argument parsing, file handling, and process management. DevOps automation scripts combine shell integration with Python logic to orchestrate deployments, monitor systems, and handle alerts.

The concepts that feel abstract right now will click into place the moment you start building something real. That is why the best way to learn is to pick a small project that solves a problem you actually have — even something simple like a personal expense tracker or a file organizer — and build it using everything you have learned so far.

Practice Exercise

Before moving to the next part, write a small program that uses what you learned in this section. Do not copy from anywhere. Start with a blank file and build it from memory. The struggle is the learning. If you get stuck, read the code examples again — do not just copy them. Understand each line, then close the examples and write the program yourself. This is how programming actually sticks.

Nested Conditionals and When to Avoid Them

Conditional statements can be nested — an if statement inside another if statement. This is sometimes necessary, but deeply nested conditions (three or more levels deep) are a code smell: they make code hard to read, test, and maintain. When you find yourself nesting deeply, look for ways to restructure using early returns, combining conditions with and/or, or extracting logic into separate functions. A well-written conditional block reads almost like a sentence describing a decision.

The Ternary Operator for Simple Decisions

For simple two-way decisions, Python offers a concise one-line syntax called the conditional expression or ternary operator:

Ternary Expression
# Traditional approach
if age >= 18:
    status = "adult"
else:
    status = "minor"

# Ternary expression - same result, one line
status = "adult" if age >= 18 else "minor"
print(status)

# Works well for simple assignments
discount = 0.2 if is_member else 0.0
label = "Pass" if score >= 40 else "Fail"

Use ternary expressions when the logic is genuinely simple and the one-liner improves readability. Avoid them for complex conditions — the multi-line version is clearer when the logic has nuance.

Practice Exercise

Build a grade calculator: take a student's score (0-100) as input. Use if-elif-else to determine their letter grade (A for 90+, B for 80-89, C for 70-79, D for 60-69, F below 60). Then print a message that includes the score, the letter grade, and whether they passed (score 40 or above). Add a special message for perfect scores (100) and for failing scores below 30.

Disclaimer: This content is for educational purposes only. SRJahir Tech does not guarantee any specific outcome, job placement, or exam result. Learning requires consistent effort and practical application.