BiTree
  • Search For Lessons
  • Curriculum
  • Pricing
  • For Educators
  • Become a Tutor
  • About
  • Contact
Log InGet Started

Questions, concerns, bug reports, or suggestions? We read every message, write to us at [email protected].

More ways to reach us →
BiTree

Live coding lessons for aspiring developers and security professionals.

[email protected]

(201) 785-7951

Mon–Fri, 9 AM–5 PM EST

Learn

  • Search For Lessons
  • Curriculum
  • Pricing

Company

  • About
  • For Educators & Schools
  • Become a Tutor
  • Contact Us

Legal

  • Terms of Service
  • Privacy Policy
© 2026 BiTree. All rights reserved.
Curriculum/Web Development/Python Functions and Automation
40 minBeginner

Python Functions and Automation

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.

Prerequisites:Python Data Structures

Defining and calling a function

Use def to define a function. Parameters go in parentheses; return sends a value back to the caller.

python
def greet(name):
return "Hello, " + name + "!"
message = greet("Alex")
print(message) # Hello, Alex!
print(greet("World")) # Hello, World!

Multiple parameters and default values

Parameters can have defaults; named arguments make calls more readable.

python
def calc_total(price, tax_rate=0.08):
return price + (price * tax_rate)
print(calc_total(20)) # uses default 8% tax
print(calc_total(20, tax_rate=0.10)) # 10% tax

ℹ️ Tip, one function, one job

If you can describe a function in one sentence, it's the right size. If you need "and" or "then" in the description, split it into two.

Importing built-in modules

Python ships with hundreds of useful modules. Import them with import.

python
import random
import datetime
print(random.randint(1, 6)) # roll a die
print(datetime.date.today()) # today's date

Try it: refactor your guessing game

Take last lesson's guessing-game exercise and clean it up using functions.

  1. 1

    Wrap the game logic in a function called play_round() that returns the number of guesses

  2. 2

    Write a separate function ask_yes_no(prompt) that returns True/False

  3. 3

    Use a while loop in main() to play repeatedly until ask_yes_no("Play again?") returns False

  4. 4

    Print the all-time best score from the leaderboard at the end

Quick Check

What does this function return: def f(x): print(x)?

Trick question, what does Python use when you don't write a return statement?

Sign in and purchase access to unlock this lesson.

Sign in to purchase
←Python Data Structures
Back to Web Development
Introduction to the Terminal and Linux→