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:
temperature = 32if temperature >= 30:print("Remember to stay hydrated")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:
balance = 80cost = 100if balance >= cost:print("Sufficient balance")else: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:
score = 86if score >= 90:level = "Excellent"elif score >= 80:level = "Good"elif score >= 60:level = "Pass"else:level = "Below standard"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:
score = 95if score >= 60:print("Meets the passing threshold")if score >= 90: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:
age = 20verified = Trueif age >= 18:if verified:print("You may continue")else: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:
- Does each statement header have its required colon?
- Are statements in the same block aligned?
- Which
ifdoes eachelsebelong to? - Has a statement that should run outside a branch been accidentally indented?
- 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:
status = "ready"if status == "ready":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:
age = 22has_permission = Trueif age >= 18 and has_permission:print("Access requirements met")
andrequires both conditions to be true.orrequires at least one condition to be true.notreverses a condition’s truth value.
Python uses short-circuit evaluation. For example:
items = []if items and items[0] > 0: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:
scores = [72, 88, 95]for score in scores:print(score)
For a fixed number of repetitions, use an integer sequence:
for index in range(3):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:
remaining = 3while remaining > 0:print("Run one task")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:
values = [3, -1, 5, 0, 8]for value in values:if value < 0:continueif value == 0:breakprint(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:
values = [3, -1, 5, -2]valid_values = []for value in values:if value >= 0: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:
def classify_score(score):if score >= 90:return "Excellent"elif score >= 80:return "Good"elif score >= 60:return "Pass"else:return "Below standard"
Pass a value when calling it:
result = classify_score(86)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:
def add_numbers(a, b):return a + btotal = 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:
def collect_value(value, bucket=None):if bucket is None:bucket = []bucket.append(value)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.
def classify_score(score):if score >= 90:return "Excellent"if score >= 80:return "Good"if score >= 60:return "Pass"return "Below standard"def summarize_scores(scores):results = []total = 0valid_count = 0for score in scores:if type(score) is not int:continueif not 0 <= score <= 100:continueresults.append((score, classify_score(score)))total += scorevalid_count += 1if valid_count == 0:return results, Nonereturn results, total / valid_countrecords, average = summarize_scores([95, 82, -5, 60, 101])for score, level in records:print(score, level)if average is None:print("No valid scores")else: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:
assert classify_score(59) == "Below standard"assert classify_score(60) == "Pass"assert classify_score(80) == "Good"assert classify_score(90) == "Excellent"records, average = summarize_scores([])assert records == []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.
