Functions and Modules with Copilot Prompts

Functions and modules are two of the most important building blocks in Python. They help you organize your code, avoid repeating yourself, and use powerful tools written by others.

In this lesson, you'll learn to:

  • Write your own functions
  • Use arguments in different ways
  • Create small, anonymous functions (lambdas)
  • Import and use built-in modules

Let’s get started using simple Copilot prompts to explore each!

Defining Functions

A function is a reusable block of code that performs a specific task. You "define" a function once, and then "call" it whenever you need it.

Prompt

1
# Write a Python function that calculates the factorial of a number

When you type this comment and start your function (e.g., typing def factorial(), Copilot might suggest:

python
1
2
3
4
5
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

Explanation

  • def factorial(n): Starts defining a function named factorial that takes one argument, n.
  • if n == 0 or n == 1: Checks if n is 0 or 1 (the factorial of both is 1).
  • return 1: Returns 1 in these cases.
  • else: For all other numbers, it multiplies n by the factorial of n - 1 (this is called recursion).

Practice

Try calling:

python
1
2
print(factorial(5))  # Output: 120
print(factorial(0))  # Output: 1

Function Arguments

Python functions can accept different kinds of arguments:

  • Default arguments: Use a default value if no value is given.
  • Keyword arguments: Call a function by specifying parameter names.
  • Variable-length arguments: Accept any number of values.

Prompt

1
# Create a function that accepts any number of arguments and returns their sum

Copilot might suggest:

python
1
2
def sum_all(*args):
    return sum(args)

Explanation

  • *args: Collects all extra positional arguments into a tuple called args.
  • sum(args): Adds up all values inside args and returns the result.

Practice

Try:

python
1
2
print(sum_all(1, 2, 3))         # Output: 6
print(sum_all(5, 10, 15, 20))   # Output: 50

Default and Keyword Arguments Example

python
1
2
def greet(name, message="Hello"):
    return f"{message}, {name}!"

Here, message has a default value "Hello". You can call:

python
1
2
print(greet("Alice"))                  # Output: Hello, Alice!
print(greet("Bob", message="Hi"))     # Output: Hi, Bob!

Lambda Functions

A lambda function is a small, anonymous function you can write in one line. It’s often used when you need a quick, simple function.

Prompt

1
# Write an example using lambda to sort a list of tuples

Copilot might suggest:

python
1
2
3
4
5
6
points = [(2, 3), (1, 2), (4, 1), (3, 5)]

# Sort by the second value in each tuple
points_sorted = sorted(points, key=lambda x: x[1])

print(points_sorted)

Explanation

  • lambda x: x[1]: Defines a function that takes x (a tuple) and returns its second value.
  • sorted(points, key=lambda x: x[1]): Sorts the list based on the second item in each tuple.

Practice

Try sorting by the first element instead:

python
1
2
points_sorted = sorted(points, key=lambda x: x[0])
print(points_sorted)

Importing and Using Modules

A module is a file with Python code that you can reuse. Python has many built-in modules, like math, which provides mathematical functions.

Prompt

1
# Show how to import math and use sqrt and ceil functions

Copilot might suggest:

python
1
2
3
4
5
6
7
8
9
import math

number = 7.5

# Square root
print(math.sqrt(number))  # Output: 2.738...

# Ceiling (round up)
print(math.ceil(number))  # Output: 8

Explanation

  • import math: Brings in the math module so you can use its functions.
  • math.sqrt(number): Finds the square root.
  • math.ceil(number): Rounds a number up to the nearest integer.

Practice

  • Try math.floor() to round down.
  • Explore other functions like math.pow() or math.pi.

Key Takeaways

  • Use functions to organize and reuse code.
  • Understand how to work with arguments: default, keyword, and variable-length.
  • Try lambda functions for small, quick tasks.
  • Use modules to access extra tools without writing everything from scratch.

Mini Challenge

Prompt

1
# Write a Python function that takes a list of numbers and returns a new list with each number squared. Then use math.sqrt on each squared number and return the final list.

Work with Copilot to generate the function, test it with different lists, and check the outputs!

Frequently Asked Questions