Functions in Python: Pair Programming
A function is a reusable block of code that performs a specific task. You can think of it as a way to organize and structure your code, so you can easily run the same set of instructions whenever you need. Functions can take input (parameters) and often return output (return values).
Instructions for pair programming:
Work in pairs to complete this worksheet. For each section:
- One person should write the code, while the other explains the logic and gives instructions.
- Switch roles after each exercise.
- Discuss your answers and break down each function to ensure you both understand it thoroughly.
Reflection:
After completing each exercise:
- Discuss with your partner how the function worked.
- Identify any challenges you faced and how you overcame them.
- Make sure you both fully understand each solution.
1. Simple Functions Without Parameters
Let’s start with the simplest form of a function: one that performs an action but doesn’t take any inputs or return anything.
Example:
def greet():
print("Hello! Welcome to the program.")This function is called greet, and all it does is print a greeting message. To call this function and make it run, you just write its name followed by parentheses:
greet()Output:
Hello! Welcome to the program.
Questions:
- Does this function take any parameters?
- What word do you need to write to call the function?
- What happens when this function is called?
2. Functions With Parameters
Most functions need input to do something useful. Parameters are the inputs you provide to a function to customize its behavior. When you call a function, you can pass arguments to these parameters.
Example:
def greet_person(name):
print(f"Hello, {name}! Welcome to the program.")Here, the function greet_person takes one parameter called name. When you call the function, you pass a specific name as the argument:
greet_person("Alice")Output:
Hello, Alice! Welcome to the program.In this case, the input name is "Alice", and the function uses it to create a personalized message.
Questions:
- What parameter does this function take?
- What does the function do with the parameter?
- Does this function return any value?
Extra Exercise: Modify the function so that it returns the greeting as a string
3. Functions With Return Values
Sometimes, you want a function to perform a calculation or process and then return a result. You can use the return statement to send a value back from a function.
Example:
def add_numbers(a, b):
return a + bIn this example, add_numbers takes two numbers, adds them together, and returns the result. To use this function and get the result, you need to call it and store the result in a variable:
result = add_numbers(5, 7)
print(result)Output:
12Here, the function returns 12, which is stored in the variable result, and then printed.
Questions:
- How many parameters does this function have? What are their names and data types?
- What value is returned from this function?
Extra Exercise: Modify the function so that it can add 2 floats together and return them
4. Functions Combining Parameters and Return Values
You can combine input parameters and return values to create more complex and useful functions.
Example:
Let’s look at a function that calculates the total cost of an item, given its price and quantity:
def calculate_total(price, quantity):
return price * quantityTo call this function, you provide the price and quantity as arguments:
total_cost = calculate_total(10.99, 3)
print(f"The total cost is: £{total_cost}")Output:
The total cost is: £32.97Here, the function takes the price of an item and the quantity, multiplies them, and returns the total cost.
Questions:
- How many parameters does the function have?
- What is the function returning?
- How can you call this function with different values to caluclate a different total?
Programming Exercises
Exercise 1: Simple Function
Write a function called goodbye that prints "Goodbye! Thanks for using the program."
Task:
- Define the function
goodbye(). - Call the function to see the output.
Exercise 2: Function With Parameters
Write a function called welcome_user that takes a user’s name as a parameter and prints "Welcome, [name]!"
Task:
- Define the function
welcome_user(name). - Call the function with the name
"John".
Exercise 3: Function With Return Value
Write a function called calculate_area that takes two parameters: length and width. The function should calculate the area of a rectangle and return it.
Task:
- Define the function
calculate_area(length, width). - Call the function with the arguments
5and10, and store the result in a variable. - Print the result.
Exercise 4: Calculator Functions
Write a series of functions that perform basic arithmetic operations. Each function should take two parameters and return the result.
Addition Function
Write a function called add(a, b) that returns the sum of a and b.
Example Call:
result = add(5, 3) # result should be 8Subtraction Function
Write a function called subtract(a, b) that returns the difference between a and b.
Example Call:
result = subtract(10, 4) # result should be 6Multiplication Function
Write a function called multiply(a, b) that returns the product of a and b.
Get Icodewithben’s stories in your inbox
Join Medium for free to get updates from this writer.
Example Call:
result = multiply(7, 2) # result should be 14Division Function
Write a function called divide(a, b) that returns the quotient of a divided by b. Make sure to handle division by zero.
Example Call:
result = divide(9, 3) # result should be 3Bonus Task:
After writing all the functions, create a simple calculator program that asks the user to enter two numbers and choose an operation (addition, subtraction, multiplication, or division). Use the appropriate function based on the user’s input and display the result.
Programming Problems
Now, work with your partner to write and solve the following programming problems. Alternate who writes the code and who provides instructions.
Break It Down into Smaller Tasks
Thinking logically and concurrently
Following a structured programming approach there are 3 basic structures you can follow to structure your program:
- Sequence — one statement after another
- Selection — if…then…else and switch/case
- Iteration — Iteration (while, do…until and for loops)
Tools for designing and understanding programs
- Trace Tables (where you write the main variables in the program and trace the contents of them on every loop)
- Flow charts
Exercise 0: Counting game
Two people play a counting game. The rules of the game are as follows:
- The first player starts at 1.
- Each player may choose one, two, or three numbers on their turn, and the numbers must be in ascending order.
- Players take it in turns to choose.
- The player who chooses “15” loses the game.
For example, if the first player chooses three numbers (1, 2, 3), then the second player could choose one number (4), two numbers (4, 5), or three numbers (4, 5, 6). The first player then takes another go.
- Write an algorithm first with a flow chart, then pseudocode and then code that allows two players to play this game. The algorithm should:
- Alternate between player 1 and player 2.
- Ask the player how many numbers they would like to choose, ensuring that this is between 1 and 3.
- Display the numbers that the player has chosen.
- Display a suitable message to say which player has won once the number “15” has been displayed.
Steps to Solve This Problem
Step 1: Understand the Problem
Key Rules:
- Players take turns starting from the number
1. - Each player must choose between 1, 2, or 3 numbers in ascending order.
- The game ends when someone chooses
15, and that player loses.
- Inputs: The number of numbers a player chooses (1, 2, or 3).
- Outputs: The numbers chosen by the player, and a message indicating the winner.
Exercise 1: Shark Problem
Your friend invites you out to a cool floating pontoon about 1 km off the beach. As you plunge out of the slide into the water, you see a shark hovering nearby! You need to figure out if you can make it to the pontoon before the shark gets to you.
- Write out the steps or use a flow chart
- Write a function that takes in 5 variables:
def shark(pontoon_distance, shark_distance, you_speed, shark_speed, dolphin):
pass # Don't get eaten!pontoonDistance: How far you need to swim (in meters).sharkDistance: Distance from the shark to the pontoon.youSpeed: How fast you can swim (in meters/second).sharkSpeed: How fast the shark moves (in meters/second).dolphin: A boolean, if true, the shark’s speed is halved (due to a dolphin distracting it).
Formula:
Time = Distance ÷ Speed.
Compare the time for you and the shark to reach the pontoon.
Objective: If you make it, return "Alive!", otherwise return "Shark Bait!".
This comes from this problem: Training on Holiday VI — Shark Pontoon | Codewars
Test data:
When you call Shark with the values below it should return “Alive!” or “Shark Bait!”. These are call unit test cases:
// Call the function like this, and you should get this back:
Shark(12, 50, 4, 8, True) # Expected result: "Alive!"
Shark(12, 50, 4, 8, False) # Expected result: "Alive!"
Shark(7, 55, 4, 16, True) # Expected result: "Alive!"
Shark(24, 0, 4, 8, True) # Expected result: "Shark Bait!"Exercise 2: Mango Problem
You are at a market that offers a “3 for 2” deal on mangoes.
Write a function that calculates the total cost for a given number of mangoes, considering the offer. First write out the steps of the algorithm
Price of Mangoes (If statements): Training on Price of Mangoes | Codewars
Function signature:int Mango(int quantity, int price)
Examples:
Mango(2, 3) ==> 6 // No free mango
Mango(3, 3) ==> 6 // 1 free mango
Mango(5, 3) ==> 12 // 1 free mangoExercise 3: Even or Odd
Write a function that takes an integer as an argument and returns "Even" for even numbers and "Odd" for odd numbers.
Function signature:string EvenOrOdd(int number)
Examples:
EvenOrOdd(2) ==> "Even"
EvenOrOdd(3) ==> "Odd"Exercise 4: Duty Free Whiskey
The goal is to determine how many bottles of duty-free whiskey you need to buy to cover the cost of your holiday, using the savings from the duty-free discount.
Function signature:int DutyFree(int normPrice, int discount, int holidayCost)
Examples:
DutyFree(10, 10, 500) ==> 500
DutyFree(12, 50, 1000) ==> 166Exercise 5: Get Planet Name by ID
Write a function that takes a planet ID as input and returns the name of the corresponding planet.
Function signature:string GetPlanetNameByID(int id)
Examples:
GetPlanetNameByID(3) ==> "Earth"






