Defining functions
def greet(name):
return f"Hello, {name}!"
message = greet("Besa")
print(message) # Hello, Besa!
def starts a function, the indented lines are its body, and return sends a value back. A function without return gives back None.
Parameters and default values
def area(width, height=1):
return width * height
print(area(4, 3)) # 12
print(area(5)) # 5, height defaults to 1
print(area(height=2, width=6)) # 12, named arguments
Default values make parameters optional. Named arguments make calls easier to read when a function takes several values.
Dictionaries
A dictionary maps keys to values:
capitals = {"Albania": "Tirana", "Kosovo": "Pristina", "Italy": "Rome"}
print(capitals["Albania"]) # Tirana
capitals["Greece"] = "Athens" # add or change
print(capitals.get("Spain", "unknown")) # unknown, no error
for country, city in capitals.items():
print(country, "-", city)
Reading a missing key with square brackets raises a KeyError; .get() returns a default instead.
Project: count words
This function counts how often each word appears in a text and returns the most common ones:
def word_counts(text):
counts = {}
for word in text.lower().split():
word = word.strip(".,!?;:\"'")
if word:
counts[word] = counts.get(word, 0) + 1
return counts
def top_words(text, n=3):
counts = word_counts(text)
return sorted(counts.items(), key=lambda pair: pair[1], reverse=True)[:n]
poem = "The sun is warm. The sea is blue, and the sky is blue too."
for word, count in top_words(poem):
print(word, count)
Output: the 3, is 3, blue 2. The key= argument tells sorted to order the pairs by their count.
Writing good functions
- Do one job per function, and name it with a verb:
calculate_total,is_valid_email. - Pass data in as parameters and return results, instead of changing global variables.
- Keep them short. If a function no longer fits on your screen, split it.
- Test them with small examples, including edge cases like an empty string.
Try it yourself
In Unays Code, write a function grade(score) that returns "A" to "F", then use a dictionary to count how many students got each grade from a list of scores.
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].