Why this matters
You reach for Python when you want to get something done without fighting the language. It is the tool people use to rename a thousand files, scrape a web page, clean a messy spreadsheet, or glue two services together. Because the syntax stays close to plain English, you spend your mental energy on the problem instead of on punctuation.
In data science and machine learning, Python is the default. Libraries such as pandas, NumPy, and scikit-learn let you describe operations on whole tables of data in a few lines. Researchers and analysts use it because they can go from an idea to a working experiment quickly, then share the result as readable code.
Web developers use Python through frameworks like Django and Flask, and system administrators use it for automation and configuration. It is rarely the fastest language at runtime, but programmer time usually costs more than computer time, and Python optimizes for your time.
The big picture
Think of a Python program as a conversation between your code and objects that live in memory. Every value, whether a number, a list, or a function, is an object with a type and behaviour. You bind names to these objects with the assignment operator, and you ask objects to do things by calling methods or passing them to functions.
Python is dynamically typed, which means you do not declare a variable's type ahead of time. The type belongs to the value, not the name, so a name can point to a number and later to a string. This flexibility is convenient, but it also means mistakes that a compiler would catch show up only when the code runs.
Indentation is part of the syntax. Instead of braces, Python uses whitespace to show which lines belong inside a function, an if statement, or a loop. This gives Python its clean look, but it also means you must be consistent about spaces, or the program will not run.
Core ideas
Variables and names
A variable is a name you attach to a value so you can use it later. You create one with a single equals sign, like count = 10. The equals sign does not mean equality here; it means store this value under this name. From then on, whenever Python sees count, it looks up the value.
Names can hold anything: numbers, text, lists, or even functions. You can reassign a name at any time, and Python simply points it at the new value. Choose descriptive names such as user_age rather than cryptic ones, because you will read your code far more often than you write it.
count = 10
name = 'Ada'
count = count + 1
print(name, count)
Watch out. Do not expect x = x + 1 to fail because it looks impossible in maths. In Python it is a normal instruction: compute the right side first, then store the result back in x.
Numbers and strings
Python has integers for whole numbers and floats for decimal numbers. Arithmetic works as you would expect with plus, minus, multiply, and divide. One surprise is that division with / always produces a float, even when the answer is a whole number, while // performs floor division and drops the remainder.
Strings hold text. You can write them with single or double quotes, join them with plus, repeat them with multiply, and pull out pieces with indexing and slicing. Python counts positions from zero, so the first character is at index 0. Strings are immutable, which means you cannot change a character in place.
price = 20
tax = 1.08
total = price * tax
greeting = 'Hello'
print(greeting[0], round(total, 2))
Watch out. A common surprise is '2' + 3 raising an error. Strings and numbers are different types, so convert explicitly with int() or str() when you need to combine them.
Lists, tuples and dicts
A list is an ordered collection you can change: add items, remove them, or replace them. A tuple is like a list but fixed once created, which is useful for coordinates or database rows that should never change. Both keep items in order and are indexed from zero.
A dictionary stores key-value pairs, letting you look up a value by a meaningful key instead of a numeric position. Use lists when order matters, dictionaries when you have labels for your data. All three are built into the language, so you reach for them constantly.
fruits = ['apple', 'pear']
fruits.append('mango')
point = (10, 20)
person = {'name': 'Ada', 'age': 36}
print(fruits[0], person['name'])
Watch out. Copying a list with b = a does not make a new list; both names point to the same object. Use a.copy() or list(a) when you need an independent copy.
Conditionals
An if statement lets your program choose. You write a condition, a colon, and an indented block that runs only when the condition is true. Use elif to check more possibilities and else as the final fallback. Conditions evaluate to True or False, the two values of the bool type.
You combine conditions with and, or, and not, and you can test membership with in. Python treats empty values such as 0, empty strings, and empty lists as falsey, which lets you write short checks. Be careful, though: is compares identity while == compares values, and the two are not interchangeable.
temp = 30
if temp > 25:
print('hot')
elif temp > 15:
print('warm')
else:
print('cold')
Watch out. Do not write if x = 5 with a single equals sign. That is assignment and is a syntax error inside a condition. Comparison uses two equals signs, as in if x == 5.
Loops
A for loop walks through a sequence and runs the same block once per item. It is the workhorse of Python because you rarely need to manage an index yourself. Use range() when you need to repeat something a fixed number of times, and enumerate() when you need both the index and the item.
A while loop keeps going as long as a condition stays true, which suits situations where you do not know the number of repetitions in advance. Inside any loop, break exits early and continue skips to the next round. Loops can nest, but deeply nested loops are often a sign that a helper function would read better.
for i, fruit in enumerate(['apple', 'pear']):
print(i, fruit)
total = 0
for n in range(1, 5):
total += n
Watch out. Beware of changing a list while you loop over it. Removing items shifts positions and can skip elements. Iterate over a copy, such as for item in items[:], when you plan to modify the original.
Functions
A function is a named, reusable block of work. You define it with def, give it a name and a parameter list, and return a result with return. Calling the function runs its body with the arguments you supply. Functions let you name a concept once and use it everywhere, which is the single biggest step toward writing clean code.
Parameters are the placeholders in the definition; arguments are the real values you pass in. Python matches positional arguments in order, and you can also use keyword arguments by name. Good functions do one thing, have a clear name, and avoid reaching outside themselves to change unrelated state.
def greet(name, punctuation='!'):
return 'Hello, ' + name + punctuation
print(greet('Ada'))
print(greet('Bob', '?'))
Watch out. Forgetting return makes a function hand back None. If you see None where you expected a value, check that every code path actually returns something.
Modules and imports
A module is simply a .py file whose contents you can reuse elsewhere. You bring it in with import, then access its functions and values with dot notation. The standard library ships with modules for dates, file paths, randomness, JSON, and hundreds of other tasks, so check there before writing something from scratch.
You can import a whole module, import selected names with from module import name, or give a module a shorter alias with as. Keeping imports at the top of a file makes dependencies clear. When you run a file directly, its name is __main__, a fact you will use constantly in real projects.
import math
from datetime import date
print(math.sqrt(16))
print(date.today())
Watch out. Naming your own file math.py or json.py shadows the standard library module and produces baffling errors. Avoid names that collide with built-in modules.
Errors and exceptions
When something goes wrong, Python raises an exception, which stops the program unless you catch it. A try block wraps the risky code, and an except block says what to do if a particular error occurs. Catching the specific exception is better than catching everything, because broad catches hide real bugs.
You can also raise your own exceptions with raise to signal invalid input, and use a finally block for cleanup that must run either way. Reading a traceback from the bottom up is a skill worth learning: the last line tells you the error type, and the lines above show the chain of calls that led there.
try:
value = int('not a number')
except ValueError:
print('That was not a number')
finally:
print('Done')
Watch out. Never use a bare except with no error type as a quick fix. It swallows keyboard interrupts and genuine bugs. Catch the specific error you expect.
Functions
Functions are the main way you organize Python code. You have already seen that def creates one and return sends a value back, but there is much more to how functions behave. Understanding arguments, scope, and a few advanced forms will let you read almost any Python library and write your own with confidence.
The ideas here build on each other. First you learn to pass information in and out, then you see where names live, and finally you meet functions that produce or accept other functions. That last idea sounds abstract, but it is exactly what makes decorators, callbacks, and most frameworks work.
Defining and calling
You define a function with def, its name, and a parenthesized parameter list, followed by a colon. The indented body is what runs when you call it. Calling means writing the name with parentheses and supplying arguments. The function runs from top to bottom, then returns control to the caller.
A function can be called many times, and each call gets its own local variables. That isolation is what makes functions safe to reuse. Give functions verb-like names such as calculate_total so the call site reads like a sentence.
def add(a, b):
return a + b
result = add(2, 3)
print(result)
Positional and keyword arguments
By default, arguments match parameters by position. The first argument fills the first parameter, and so on. Keyword arguments let you name each one when you call, like greet(name='Ada'), which makes the call self-documenting and lets you skip the order.
You can mix the two, but positional arguments must come first. Keyword arguments are especially helpful for functions with several optional settings, where remembering the order would be error prone. They also make future changes to the parameter list less risky.
def greet(title, name):
return title + ' ' + name
print(greet('Dr', name='Ada'))
Default arguments
You can give a parameter a default value with an equals sign in the definition. When the caller omits that argument, Python uses the default. This lets one function serve common cases with a short call while still allowing customization when needed.
Defaults are evaluated once, when the function is defined, not each time it is called. For simple unchanging values like numbers and strings that is harmless. For mutable values like lists it causes a famous bug, which you will see in the mistakes below.
def power(x, exponent=2):
return x ** exponent
print(power(3))
print(power(3, 3))
*args and **kwargs
Sometimes you do not know how many arguments a caller will pass. Prefixing a parameter with a single star collects extra positional arguments into a tuple, conventionally called args. Prefixing with two stars collects extra keyword arguments into a dictionary, conventionally called kwargs.
These forms let you write flexible functions that forward arguments to another function. Many libraries use them in decorators and wrappers, where the wrapper should accept anything the wrapped function accepts. Use them sparingly in your own code, since clear named parameters are easier to understand.
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3))
Return values
The return statement sends a value back to the caller and ends the function immediately. You can return any object, including lists and dictionaries. A function with no return still returns the special value None, so always be deliberate about what you hand back.
Python can return several values by separating them with commas, which actually builds a tuple you can unpack in one line. Returning early is a useful way to handle edge cases without wrapping the rest of the function in an else block.
def minmax(values):
return min(values), max(values)
low, high = minmax([3, 1, 9])
print(low, high)
Scope and the LEGB rule
Scope decides where a name can be seen. Python follows the LEGB rule: it looks in Local scope first, then Enclosing function scope, then Global module scope, then Built-in names. The first match wins, which is why a local name can shadow a global one.
Reading a global from inside a function works fine. Assigning to it does not, because assignment creates a local name. Use global to modify a module-level name and nonlocal to modify one in an enclosing function. Relying on globals heavily makes functions harder to test and reuse.
count = 0
def bump():
global count
count += 1
bump()
print(count)
Closures
A closure is a function that remembers variables from the scope where it was created, even after that scope has finished. If an inner function refers to a variable from its enclosing function, Python keeps that variable alive alongside the function.
Closures let you configure a function once and reuse it. For example, you can build a multiplier that captures a factor and returns a function that multiplies by it. This is the foundation of decorators and of many callback patterns.
def make_multiplier(factor):
def multiply(x):
return x * factor
return multiply
triple = make_multiplier(3)
print(triple(5))
Decorators and lambda
A lambda is a small anonymous function written with lambda followed by parameters and an expression. It is useful for short functions you pass to tools like sorted, where naming the function would add noise. Keep lambdas simple; anything complex deserves a def.
A decorator is a function that takes a function and returns a new one, usually with added behaviour such as logging or timing. You apply it with the at-sign above a definition. Decorators are just closures and higher-order functions in action, which is why understanding those ideas matters.
def loud(fn):
def wrapper():
return fn().upper()
return wrapper
@loud
def hello():
return 'hi'
print(hello())
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
def
User-defined form
You use def to create your own named function: a reusable block of code that takes inputs and returns a result. Defining it once lets you call it as many times as you need, which keeps your programs short and easy to read.
| Syntax | def name(parameters):
body |
|---|---|
| Parameters | name — The identifier you call the function by parameters — Comma-separated input names, optional |
| Returns | The value given by a return statement, or None if there is no return. |
def greet(name):
return "Hello, " + name + "!"
print(greet("Ada"))
What you can do with it. Package a repeated calculation into one callable name Build larger programs from small, testable pieces Give a block of code a clear, self-documenting label
Choose it when. Choose def when you need a named, reusable piece of logic with a clear signature rather than a tiny one-off expression.
| Mistake | Fix |
|---|---|
| Forgetting the colon after the parameter list | End the def line with a colon and indent the body |
| Calling the function before it is defined | Define the function earlier in the file than the call |
lambda
User-defined form
A lambda makes a small anonymous function in a single line. You reach for it when a function is so short that naming it would add more noise than clarity, such as a quick sort key or a tiny callback.
| Syntax | lambda parameters: expression |
|---|---|
| Parameters | parameters — Comma-separated input names before the colon expression — The single expression whose value is returned |
| Returns | The value of the expression, automatically returned. |
double = lambda x: x * 2
print(double(5))
nums = [1, 2, 3]
print(list(map(lambda n: n + 1, nums)))
What you can do with it. Pass a tiny key function to sorted or max Write a short callback for map or filter Define quick inline sort keys for dictionaries
Choose it when. Choose lambda for a throwaway one-line function rather than def when the logic has several steps or needs a name.
| Mistake | Fix |
|---|---|
| Putting statements like return or loops inside a lambda | Use def instead; a lambda body must be a single expression |
| Expecting a docstring or several statements to fit | Keep lambdas tiny, or switch to def when you need documentation |
closure (nested function)
User-defined form
A closure is a function defined inside another function that remembers variables from the outer scope. You use it when you want a function that carries private state with it, without using a global variable.
| Syntax | def outer():
...
def inner():
...
return inner |
|---|---|
| Returns | Usually the inner function, which keeps access to the outer variables after the outer call ends. |
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = make_counter()
print(c(), c())
What you can do with it. Build a counter or accumulator with hidden state Create function factories that customize behavior Write decorators that wrap other functions
Choose it when. Choose a closure when a function must remember state between calls rather than passing that state in every time.
| Mistake | Fix |
|---|---|
| Reassigning an outer variable without nonlocal | Declare nonlocal count inside the inner function before changing it |
| Expecting the outer variable to reset on every inner call | The captured value persists; call the outer function again for fresh state |
decorator
User-defined form
A decorator wraps another function to add behavior before or after it runs. You use it to layer concerns like logging, timing, or access checks without editing the original function's body.
| Syntax | @decorator_name
def function_name(...):
... |
|---|---|
| Parameters | decorator_name — A function that takes a function and returns a wrapper function_name — The function being wrapped |
| Returns | The wrapper function replaces the original under the same name. |
def announce(fn):
def wrapper():
print("starting")
return fn()
return wrapper
@announce
def hello():
print("hi")
hello()
What you can do with it. Add timing or logging around existing functions Enforce checks such as authentication before a call Register functions in a plugin or route table
Choose it when. Choose a decorator when several functions need the same wrapper behavior rather than copying that code into each one.
| Mistake | Fix |
|---|---|
| Forgetting to call fn() inside the wrapper | Invoke fn() in the wrapper or the original body never runs |
| Losing the original name and docstring | Use functools.wraps(fn) on the wrapper |
generator function
User-defined form
A generator function uses yield to produce values one at a time, pausing between them. You use it to work with large or even endless sequences without storing everything in memory at once.
| Syntax | def name(...):
yield value |
|---|---|
| Returns | A generator iterator that yields values lazily as you iterate it. |
def evens(limit):
n = 0
while n < limit:
yield n
n += 2
for x in evens(10):
print(x)
What you can do with it. Stream large files line by line Produce an endless sequence of values lazily Build pipeline-style data processing with low memory
Choose it when. Choose a generator when you need values on demand rather than building a full list up front.
| Mistake | Fix |
|---|---|
| Using return value to send data back to the caller | Use yield to emit values; return only stops the generator |
| Expecting the values to be a reusable list | A generator is consumed once; call the function again or wrap it in list() |
len
Built-in function
len tells you how many items or characters are in a value. It is the quickest way to measure the size of a string, list, tuple, dictionary, or set, so you can make decisions before looping.
| Syntax | len(object) |
|---|---|
| Parameters | object — The value whose length is measured |
| Returns | An integer: the number of items or characters. |
text = "hello"
print(len(text))
items = [10, 20, 30]
print(len(items))
What you can do with it. Check whether a collection is empty before looping Validate that input meets a minimum length Report sizes in logs or user messages
Choose it when. Choose len when you need the size of a collection rather than iterating just to count.
| Mistake | Fix |
|---|---|
| Calling len on an integer or boolean | len only works on sized objects such as strings and collections |
| Counting bytes instead of characters for Unicode text | len counts characters; encode first if you truly need a byte count |
range
Built-in function
range produces a sequence of integers you can loop over. You use it when you want to repeat an action a set number of times or walk through the indexes of a list.
| Syntax | range(start, stop, step) |
|---|---|
| Parameters | start — Inclusive first value; defaults to 0 stop — Exclusive upper bound step — Difference between values; defaults to 1 |
| Returns | A range object that yields integers on demand. |
for i in range(3):
print(i)
for n in range(1, 10, 2):
print(n)
What you can do with it. Repeat a task a fixed number of times Iterate over list indexes Generate number sequences with a custom step
Choose it when. Choose range for numeric loops rather than building an explicit list of indexes.
| Mistake | Fix |
|---|---|
| Expecting stop to be included | range stops before stop, so range(3) gives 0, 1, 2 |
| Using a step of zero | step must be a nonzero number |
sorted
Built-in function
sorted returns a new list with the items in order. You use it when you need a sorted copy and want to leave the original collection untouched, which helps avoid surprising side effects.
| Syntax | sorted(iterable, key=None, reverse=False) |
|---|---|
| Parameters | iterable — The items to sort key — A function computing the sort key reverse — True to sort descending |
| Returns | A new sorted list. |
names = ["Zoe", "Ana", "Mia"]
print(sorted(names))
words = ["pear", "apple", "fig"]
print(sorted(words, key=len))
What you can do with it. Order a list of names or numbers for display Sort records by a field using key Produce a descending ranking with reverse
Choose it when. Choose sorted when you want a new ordered list rather than modifying the existing one.
| Mistake | Fix |
|---|---|
| Expecting the original list to change | sorted returns a new list; use list.sort() to sort in place |
| Mixing incomparable types such as strings and numbers | Convert to a common type or supply a key |
enumerate
Built-in function
enumerate pairs each item with its index as you loop. You use it when you need both the position and the value, so you can avoid managing a separate counter by hand.
| Syntax | enumerate(iterable, start=0) |
|---|---|
| Parameters | iterable — The items to loop over start — The number to count from; defaults to 0 |
| Returns | An iterator of (index, value) tuples. |
fruits = ["apple", "banana"]
for i, fruit in enumerate(fruits):
print(i, fruit)
for n, item in enumerate(fruits, start=1):
print(n, item)
What you can do with it. Number items in a report or menu Track indexes while iterating Build dictionaries from index to value
Choose it when. Choose enumerate when you need the index during a loop rather than calling index() inside it.
| Mistake | Fix |
|---|---|
| Unpacking into the wrong number of variables | Use two variables: for i, value in enumerate(items) |
| Forgetting start defaults to zero | Pass start=1 when you want human-friendly numbering |
zip
Built-in function
zip combines several iterables into tuples, pairing items by position. You use it when you need to walk two or more sequences together instead of writing nested loops.
| Syntax | zip(*iterables) |
|---|---|
| Parameters | iterables — Two or more sequences to pair element by element |
| Returns | An iterator of tuples, one item from each input. |
names = ["Ada", "Bob"]
scores = [90, 75]
for name, score in zip(names, scores):
print(name, score)
pairs = list(zip(names, scores))
What you can do with it. Pair parallel lists into records Build dictionaries from keys and values Iterate over two collections in lockstep
Choose it when. Choose zip when you need corresponding items from multiple sequences rather than nested loops.
| Mistake | Fix |
|---|---|
| Assuming zip stops at the longest input | zip stops at the shortest; use itertools.zip_longest to pad |
| Expecting a list back | zip returns an iterator; wrap it in list() to see the pairs |
map
Built-in function
map applies a function to every item in an iterable. You use it when you want to transform a whole collection without writing an explicit loop, especially when the transform is simple.
| Syntax | map(function, iterable) |
|---|---|
| Parameters | function — The function applied to each item iterable — The collection of items |
| Returns | An iterator of the transformed results. |
nums = [1, 2, 3]
squares = map(lambda n: n * n, nums)
print(list(squares))
print(list(map(str, nums)))
What you can do with it. Convert every item to a new type Apply a shared calculation across a dataset Build lazy transformation pipelines
Choose it when. Choose map when the same function must run on every item rather than writing a repetitive for loop.
| Mistake | Fix |
|---|---|
| Expecting a list directly | map returns an iterator; wrap it in list() when needed |
| Reusing the iterator after it is consumed | Each map iterator is single-use; recreate it or store the results |
sum
Built-in function
sum adds up the numbers in an iterable. You use it instead of a manual accumulator loop when all you need is a final total, which makes your intent obvious at a glance.
| Syntax | sum(iterable, start=0) |
|---|---|
| Parameters | iterable — Numbers to add together start — Value added first; defaults to 0 |
| Returns | The total of all items plus start. |
nums = [1, 2, 3, 4]
print(sum(nums))
prices = [2.5, 3.0, 4.25]
print(sum(prices))
What you can do with it. Total a list of prices or scores Aggregate numeric columns of data Add a starting baseline with start
Choose it when. Choose sum when you need one final total rather than tracking intermediate results.
| Mistake | Fix |
|---|---|
| Trying to sum strings | sum is for numbers; use "".join to concatenate strings |
| Expecting a running list of partial totals | sum returns only the final total; use itertools.accumulate for running sums |
max
Built-in function
max returns the largest item from an iterable or the largest of several arguments. You use it when you need the top value quickly, without sorting the whole collection first.
| Syntax | max(iterable) or max(a, b, c) |
|---|---|
| Parameters | iterable — A collection of comparable items key — Optional function computing a comparison key |
| Returns | The largest item, or the item with the largest key. |
nums = [4, 1, 9, 2]
print(max(nums))
words = ["pear", "apple", "fig"]
print(max(words, key=len))
What you can do with it. Find the highest score or price Pick the longest string using key Compare several values passed directly
Choose it when. Choose max when you want the single largest value rather than sorting the whole collection.
| Mistake | Fix |
|---|---|
| Calling max on an empty iterable | Check that the iterable has items or supply a default |
| Comparing mixed incomparable types | Use a key that returns a comparable value |
min
Built-in function
min returns the smallest item from an iterable or the smallest of several arguments. You use it when you need the lowest value and do not care about the order of everything else.
| Syntax | min(iterable) or min(a, b, c) |
|---|---|
| Parameters | iterable — A collection of comparable items key — Optional function computing a comparison key |
| Returns | The smallest item, or the item with the smallest key. |
nums = [4, 1, 9, 2]
print(min(nums))
words = ["pear", "apple", "fig"]
print(min(words, key=len))
What you can do with it. Find the lowest price or temperature Pick the shortest string using key Compare against a lower bound in logic
Choose it when. Choose min when you need the single smallest value rather than an ordered list.
| Mistake | Fix |
|---|---|
| Calling min on an empty iterable | Check for items first or provide a default value |
| Assuming it returns all tied smallest values | min returns one item; filter the list if you need every tie |
Common mistakes here
| Mistake | Fix |
|---|---|
| Using a mutable default argument such as def add(item, items=[]). | Use None as the default and create a fresh list inside the function when the argument is None. |
| Forgetting return and wondering why the function gives None. | End every path with an explicit return of the value you need. |
| Assuming a local variable can be assigned to change a global one. | Declare global or nonlocal, or better, pass the value in and return the new value. |
| Confusing *args with keyword arguments. | Remember a single star collects positional extras into a tuple and two stars collect named extras into a dictionary. |
| Applying a decorator without returning the wrapper function. | Make the decorator return wrapper, and use functools.wraps to preserve the original name and docstring. |
The example, line by line
This short program grades a list of test scores and prints a summary using two small, focused functions.
| Code | What it does |
|---|---|
1def summarize(values): | Define a function that takes a list of numbers and will hand back two results. |
2 total = sum(values) | Add up all the values using the built-in sum function. |
3 average = total / len(values) | Divide the total by the number of items to get the mean. |
4 return total, average | Return both results as a tuple, which Python can unpack later. |
5def label(score): | Define a second function that converts one numeric score into a letter. |
6 if score >= 90: | An A starts at ninety, so check that case first. |
7 return 'A' | Return the letter for the high range and stop this call here. |
8 return 'B' if score >= 80 else 'C' | For lower scores, return B for eighty or above and C otherwise. |
9scores = [92, 78, 85, 66, 95] | Create the sample data the rest of the program will work with. |
10total, average = summarize(scores) | Call summarize and unpack its tuple into two separate names at once. |
11print('Total:', total) | Print the combined total with a short label. |
12print('Average:', round(average, 1)) | Round the average to one decimal place so the output stays tidy. |
13for score in scores: | Start a loop that visits each score in order. |
14 print(score, label(score)) | Print the score beside its letter by calling label once per item. |
def summarize(values):
total = sum(values)
average = total / len(values)
return total, average
def label(score):
if score >= 90:
return 'A'
return 'B' if score >= 80 else 'C'
scores = [92, 78, 85, 66, 95]
total, average = summarize(scores)
print('Total:', total)
print('Average:', round(average, 1))
for score in scores:
print(score, label(score))
Worked variations
A reusable utility script
When you write a script that should also be importable, put the work in functions and guard the top-level call. That way importing the file does not run the program, but running it directly does.
This pattern shows why __name__ is useful. It also keeps your main logic in a small function, which makes the script easier to test.
def main():
print('Utility started')
if __name__ == '__main__':
main()
Processing a CSV file
Python's standard library includes a csv module that handles quoting and delimiters for you. Combined with a helper function, you can read rows and derive new values without writing a parser.
Notice how each row becomes a dictionary-like object, so your code can refer to columns by name instead of position.
import csv
with open('sales.csv', newline='') as f:
for row in csv.DictReader(f):
print(row['product'], float(row['price']) * 1.2)
A small class
Classes let you bundle data and the functions that operate on it. The methods below are just functions defined inside a class, with self referring to the current object.
Reach for a class when several functions always travel together with the same data, not simply because you want to organize code.
class Counter:
def __init__(self):
self.value = 0
def click(self):
self.value += 1
return self.value
Common mistakes
| Mistake | Fix |
|---|---|
| Mixing tabs and spaces for indentation. | Use four spaces consistently and enable a formatter or editor setting that enforces it. |
| Using is to compare strings or numbers by value. | Use == for value comparison and reserve is for checking identity with None. |
| Mutating a list while iterating over that same list. | Loop over a copy, build a new list, or use a comprehension instead. |
| Naming a variable with a built-in name such as list or str. | Pick a different name so you do not shadow the built-in function. |
| Catching every exception with a bare except branch. | Catch only the specific error you expect and let unexpected ones surface. |
Practice
- Write a function that takes a list of numbers and returns the largest one without using max().
- Build a dictionary of five words and their lengths, then print them sorted by length.
- Write a program that reads a sentence and counts how many times each word appears.
- Create a decorator that prints how long a function took to run, then apply it to a slow function.