Python Basics: A Practical Guide to Conditionals, Loops, and Functions

    Learn how Python conditionals, loops, and functions work together to create clear, reusable programs. This beginner-friendly guide covers indentation, logical expressions, loop control, function inputs and return values, and a practical score-processing example with input validation and boundary tests.

    1. Understand How Programs Execute

    Before learning programming syntax, it helps to understand why code runs in a particular order. The three basic control structures are sequence, selection, and iteration:

    • Sequential execution: Statements run in the order they appear.
    • Conditional execution: Conditions determine whether a block runs or which path the program takes.
    • Repeated execution: A block runs repeatedly based on a condition or an iterable.

    Functions are not a fourth control structure on the same level. They organize code. A function can contain sequential statements, conditionals, and loops; other code executes that logic by calling the function.

    For example, a program that processes scores might iterate over each value, check whether it is valid, and then call a function to assign a grade. These building blocks combine into a complete workflow.

    2. Conditionals: Turn Rules into Explicit Decisions

    Use if to Control a Single Block

    Use if when an operation should run only under a particular condition:

    1. temperature = 32
    2. if temperature >= 30:
    3. print("Remember to stay hydrated")
    4. print("Check complete")

    The condition determines whether the indented block runs. The final line is outside that block, so it runs regardless of the condition.

    Keep these two points separate:

    • A false condition skips the block controlled by that condition.
    • Skipping a block does not end the entire program.

    This distinction becomes especially important in longer programs. To identify the scope of a condition, look at indentation—not just where a statement appears.

    Use if...else for Mutually Exclusive Outcomes

    When a decision has two possible paths, use if...else:

    1. balance = 80
    2. cost = 100
    3. if balance >= cost:
    4. print("Sufficient balance")
    5. else:
    6. print("Insufficient balance")

    Only one block runs during a single execution. The else clause has no condition of its own; it provides the fallback path when the preceding condition is false.

    Correct branch selection does not guarantee complete business rules, however. This example assumes that the balance and cost are comparable numeric values. If the cost could be negative, validate that constraint before checking the balance.

    Order Matters in if...elif...else

    Use an if...elif...else chain to select among several outcomes:

    1. score = 86
    2. if score >= 90:
    3. level = "Excellent"
    4. elif score >= 80:
    5. level = "Good"
    6. elif score >= 60:
    7. level = "Pass"
    8. else:
    9. level = "Below standard"
    10. print(level)

    Python checks the conditions in order. Once one matches, it executes that block and skips the remaining conditions in the same chain.

    The order is therefore part of the logic. If score >= 60 came first, a score of 95 would match "Pass", and the higher-score conditions would never be checked.

    For overlapping conditions like these, check the more specific case or higher threshold first, then handle broader cases.

    Also remember that independent if statements behave differently from an if...elif chain:

    1. score = 95
    2. if score >= 60:
    3. print("Meets the passing threshold")
    4. if score >= 90:
    5. print("Meets the excellent threshold")

    Each condition is evaluated separately, so both messages can appear. Use independent checks when multiple matching rules should be recorded. Use a mutually exclusive chain when the program should choose only one outcome.

    3. Colons and Indentation Define Code Structure

    Conditional statements, loop statements, and function definitions require a colon at the end of their headers. Indentation determines which statements belong to the following block:

    1. age = 20
    2. verified = True
    3. if age >= 18:
    4. if verified:
    5. print("You may continue")
    6. else:
    7. print("Verification required")

    The else aligns with the inner if, so it belongs to the verification check, not the age check.

    Use four spaces per indentation level and keep indentation consistent throughout a file. Do not mix tabs and spaces: this can cause indentation errors or make the displayed structure differ from how Python parses the code.

    When code behaves unexpectedly, check:

    1. Does each statement header have its required colon?
    2. Are statements in the same block aligned?
    3. Which if does each else belong to?
    4. Has a statement that should run outside a branch been accidentally indented?
    5. Has a statement that should repeat been placed outside the loop?

    Indentation is part of the program’s meaning, not merely its appearance.

    4. Write Conditions That Are Accurate, Not Just Valid

    Distinguish Assignment from Comparison

    Use = for assignment and == to test equality:

    1. status = "ready"
    2. if status == "ready":
    3. print("Ready to start")

    Data types also matter. The string "10" is not equal to the number 10. If input arrives as text, perform an appropriate conversion before making numeric comparisons.

    Combine Conditions to Reflect the Rules

    Common logical operators include and, or, and not:

    1. age = 22
    2. has_permission = True
    3. if age >= 18 and has_permission:
    4. print("Access requirements met")
    • and requires both conditions to be true.
    • or requires at least one condition to be true.
    • not reverses a condition’s truth value.

    Python uses short-circuit evaluation. For example:

    1. items = []
    2. if items and items[0] > 0:
    3. print("The first item is positive")

    An empty list is false in a conditional context, so Python does not evaluate the indexing operation that follows. This prevents an attempt to access the first item of an empty list.

    It does not replace all input validation, though. If the first item cannot be compared with a number, the comparison can still raise an error.

    Prioritize readability in complex conditions. Parentheses or named intermediate variables are often easier to maintain than many checks packed into one line.

    5. Loops: Keep Repeated Work Under Control

    Use for to Iterate Over Existing Data

    Use for to process items in a list, string, or another iterable:

    1. scores = [72, 88, 95]
    2. for score in scores:
    3. print(score)

    For a fixed number of repetitions, use an integer sequence:

    1. for index in range(3):
    2. print(index)

    This produces 0, 1, and 2. The stop value, 3, is excluded. Understanding this exclusive upper bound helps prevent off-by-one errors.

    Use while When State Determines Whether to Continue

    Use while when the number of iterations is not known in advance and execution depends on a condition:

    1. remaining = 3
    2. while remaining > 0:
    3. print("Run one task")
    4. remaining -= 1

    Identify three things when designing a while loop:

    • The initial state.
    • The condition that allows another iteration.
    • The statement that changes the state so the loop can eventually end.

    If the condition stays true and there is no exit path, the loop runs indefinitely. When debugging, inspect both the condition and whether a branch could skip the state update.

    Distinguish break from continue

    break exits the innermost enclosing loop. continue skips the rest of the current iteration and moves to the next one:

    1. values = [3, -1, 5, 0, 8]
    2. for value in values:
    3. if value < 0:
    4. continue
    5. if value == 0:
    6. break
    7. print(value)

    This prints 3 and 5. The negative value is skipped, and encountering 0 ends the loop, so 8 is never processed.

    Choose the control statement according to the intended rule. An invalid current record usually calls for skipping that record. Stopping the loop is appropriate when later records should no longer be processed. Confusing these actions can leave data unprocessed.

    Avoid Changing a Collection’s Structure While Iterating

    Deleting elements directly from a list while iterating over it can shift later elements and cause some to be skipped. When filtering data, building a new result is often clearer:

    1. values = [3, -1, 5, -2]
    2. valid_values = []
    3. for value in values:
    4. if value >= 0:
    5. valid_values.append(value)

    Separating reads from writes makes the behavior easier to reason about and verify.

    6. Functions: Make Logic Reusable and Testable

    Parameters Provide Input; Return Values Provide Output

    Define a function with def:

    1. def classify_score(score):
    2. if score >= 90:
    3. return "Excellent"
    4. elif score >= 80:
    5. return "Good"
    6. elif score >= 60:
    7. return "Pass"
    8. else:
    9. return "Below standard"

    Pass a value when calling it:

    1. result = classify_score(86)
    2. print(result)

    Here, score is the parameter, and 86 is the argument passed to the function. The return statement sends a result to the caller and ends the current function call.

    If a function finishes without returning a value, it returns None. For a function responsible for a calculation, check that every execution path produces the expected result.

    Printing Is Not Returning

    print displays information; return passes data back to the caller:

    1. def add_numbers(a, b):
    2. return a + b
    3. total = add_numbers(4, 6)

    If a function only prints its result, the caller cannot directly use that printed output as a return value for further calculations. Separating computation from presentation makes functions easier to reuse and test.

    Give Each Function a Clear Responsibility

    A function should focus on a clear task, such as validating data, calculating a total, or assigning a grade. A function that reads input, applies rules, prints a report, and changes external state is harder to modify.

    Define:

    • Which input types and ranges it accepts.
    • What it returns.
    • How it handles invalid data.
    • Whether it changes a supplied object or external state.

    For mutable objects such as lists, avoid mutable default arguments:

    1. def collect_value(value, bucket=None):
    2. if bucket is None:
    3. bucket = []
    4. bucket.append(value)
    5. return bucket

    When no container is supplied, this creates a new list for that call. It prevents separate calls from unintentionally sharing the same default list.

    7. Practical Example: Process a List of Scores

    The following example combines conditionals, loops, and functions. Valid scores must be integers from 0 through 100; Boolean values are not accepted as scores.

    1. def classify_score(score):
    2. if score >= 90:
    3. return "Excellent"
    4. if score >= 80:
    5. return "Good"
    6. if score >= 60:
    7. return "Pass"
    8. return "Below standard"
    9. def summarize_scores(scores):
    10. results = []
    11. total = 0
    12. valid_count = 0
    13. for score in scores:
    14. if type(score) is not int:
    15. continue
    16. if not 0 <= score <= 100:
    17. continue
    18. results.append((score, classify_score(score)))
    19. total += score
    20. valid_count += 1
    21. if valid_count == 0:
    22. return results, None
    23. return results, total / valid_count
    24. records, average = summarize_scores([95, 82, -5, 60, 101])
    25. for score, level in records:
    26. print(score, level)
    27. if average is None:
    28. print("No valid scores")
    29. else:
    30. print("Average score:", average)

    Several design choices are important here.

    First, invalid data is excluded before the main calculation, avoiding deeply nested logic. Second, only valid scores contribute to both the total and the count, keeping the average consistent. Finally, the function returns None when there is no valid data, rather than 0: “no data” and “an average of zero” are different outcomes.

    The classification function uses independent if statements but still returns only one grade. Each matching branch executes return, immediately ending the function call. To understand the actual execution path, examine both the branch structure and any early returns inside it.

    8. Test Boundaries, Not Just Typical Inputs

    Many basic programming errors occur near boundaries. For score classification and processing, check at least:

    • Values just below a threshold, such as 59, 79, and 89.
    • The thresholds themselves: 60, 80, and 90.
    • Both ends of the valid range: 0 and 100.
    • Out-of-range values.
    • An empty list and a list containing only invalid data.
    • Types that do not meet the input requirements.

    Simple assertions can verify expected behavior:

    1. assert classify_score(59) == "Below standard"
    2. assert classify_score(60) == "Pass"
    3. assert classify_score(80) == "Good"
    4. assert classify_score(90) == "Excellent"
    5. records, average = summarize_scores([])
    6. assert records == []
    7. assert average is None

    Use these assertions to check logic during development, not as a replacement for input validation. Assertions can be disabled under certain runtime settings.

    Mastering conditionals, loops, and functions is not just about remembering syntax. It means being able to explain which conditions trigger each path, which state changes allow a loop to finish, and which inputs produce which results. Clear answers to those questions help turn code that merely runs into code with predictable, maintainable behavior.