Python · Beginner
Python Programming Fundamentals: Conditionals, Loops, and Functions
Learn control flow, reusable functions, error handling, and Python modules.
Applied Machine Learning ·
This is part 3 of the Python Fundamentals series. Complete the preceding tutorial before starting.
Getting started
Use Google Colab to run the examples. See our Colab beginner guide for setup. Download the accompanying notebook and upload it to Colab. Run cells in order.
Learning objectives
- Understand conditional statements.
- Understand for loops.
- Understand while loops.
- Understand functions.
- Understand arguments and scope.
- Understand handling exceptions.
- Understand importing modules.
- Understand practical example: prediction accuracy.
Conditional statements
An if statement executes its indented block when a condition is true. Elif checks additional conditions in order, and else handles remaining cases. Use four spaces for indentation.
score = 0.87
if score >= 0.9:
print("High")
elif score >= 0.7:
print("Moderate")
else:
print("Low")
For loops
A for loop iterates over an iterable. Range produces integers up to but excluding its stop value. Enumerate supplies an index alongside each value.
for index, score in enumerate([0.8, 0.9, 0.85], start=1):
print(index, score)
for i in range(3):
print(i)
While loops
A while loop repeats while its condition remains true. Update the condition inside the loop to avoid unintended infinite execution. Break exits a loop; continue skips the remaining statements in the current iteration.
count = 0
while count < 3:
print(count)
count += 1
Functions
Functions group reusable instructions. Parameters receive inputs and return sends a result back to the caller. A function without an explicit return produces None.
def mean(values):
if not values:
raise ValueError("Expected at least one value")
return sum(values) / len(values)
print(mean([10, 20, 30]))
Arguments and scope
Default parameters allow callers to omit optional arguments. Keyword arguments identify parameters by name. Variables assigned inside a function are generally local to that function.
def meets_threshold(score, threshold=0.9):
return score >= threshold
print(meets_threshold(0.85))
print(meets_threshold(0.85, threshold=0.8))
Handling exceptions
Exceptions signal errors during execution. Use try and except to handle anticipated errors. Catch specific exception types rather than hiding every failure.
try:
number = float("invalid")
except ValueError:
print("Please provide a numeric value.")
Importing modules
Modules provide reusable functionality. Python includes a standard library, so many useful tools require no installation. Import only what you need or use the module name to make the origin clear.
import math
from statistics import mean
print(math.sqrt(25))
print(mean([1, 2, 3]))
Practical example: prediction accuracy
Combine functions, loops, comparisons and validation to calculate classification accuracy from known and predicted labels. This evaluates existing predictions rather than training a model.
def accuracy_score(actual, predicted):
if len(actual) != len(predicted) or not actual:
raise ValueError("Inputs must have equal nonzero lengths")
correct = sum(a == p for a, p in zip(actual, predicted))
return correct / len(actual)
print(accuracy_score([0, 1, 1, 0], [0, 1, 0, 0]))
Common mistakes
Keep indentation consistent, return values explicitly when needed, and ensure while loops can terminate. Avoid catching exceptions that you cannot handle.
Practice exercises
- Write a function returning the square of a number.
- Use a loop to count values greater than 0.8 in [0.7, 0.9, 0.85].
Exercise solutions
Exercise 1
def square(value):
return value ** 2
print(square(5))
Exercise 2
count = 0
for value in [0.7, 0.9, 0.85]:
if value > 0.8:
count += 1
print(count)