After this lesson, you will be able to: Write reusable functions with parameters and return values, and use them to automate repeated tasks.
Functions let you name a chunk of logic and reuse it. They are the single most important tool for keeping code readable as it grows. This lesson covers function definitions, parameters, return values, scope, and how to break a real problem into small functions.
Use def to define a function. Parameters go in parentheses; return sends a value back to the caller.
def greet(name):return "Hello, " + name + "!"message = greet("Alex")print(message) # Hello, Alex!print(greet("World")) # Hello, World!
Parameters can have defaults; named arguments make calls more readable.
def calc_total(price, tax_rate=0.08):return price + (price * tax_rate)print(calc_total(20)) # uses default 8% taxprint(calc_total(20, tax_rate=0.10)) # 10% tax
Python ships with hundreds of useful modules. Import them with import.
import randomimport datetimeprint(random.randint(1, 6)) # roll a dieprint(datetime.date.today()) # today's date
Take last lesson's guessing-game exercise and clean it up using functions.
Wrap the game logic in a function called play_round() that returns the number of guesses
Write a separate function ask_yes_no(prompt) that returns True/False
Use a while loop in main() to play repeatedly until ask_yes_no("Play again?") returns False
Print the all-time best score from the leaderboard at the end
Trick question, what does Python use when you don't write a return statement?
Sign in and purchase access to unlock this lesson.