Python / Functions

Functions in practice

Write functions with several arguments or none, put if and for inside them, and turn a flowchart into code. Baccalaureate

A function may need more than one value. List the parameters with commas between them, and pass the arguments in the same number and order. This function adds the times of three race stages, and we store the result for each team:

Python
def add_times(stage1_time, stage2_time, stage3_time):
    time = stage1_time + stage2_time + stage3_time
    return time

teamA = add_times(37.5, 62.5, 56.5)
teamB = add_times(44, 57, 64)
print(teamA)
print(teamB)
print("The fastest time is " + str(min(teamA, teamB)))
Console
156.5
165
The fastest time is 156.5
Passing fewer or more arguments than there are parameters gives a TypeError.

A function may need no value at all; write empty brackets both when you define it and when you call it:

Python
def good_evening():
    greeting = "Good evening!"
    return greeting

print(good_evening())
Console
Good evening!

if and for inside a function

The body of a function is a small program, so it can contain conditions. return ends the function at once; nothing after it runs:

Python
def grade(score):
    if score >= 85:
        return "Excellent"
    elif score >= 50:
        return "Pass"
    else:
        return "Try again"

for s in [92, 70, 40]:
    print(grade(s))
Console
Excellent
Pass
Try again

It can also contain a loop. This function multiplies a number by itself a number of times:

Python
def power(base, times):
    num = 1
    for i in range(times):
        num = num * base
    return num

print(power(3, 4))
print(power(2, 10))
Console
81
1024

From flowchart to code

Before writing a program with nested conditions, draw a flowchart to order the steps. Each shape has a match in Python:

ShapeMeaningIn Python
DiamondYes / no questionif weather == "sunny":
"No" arrowThe other pathelse:
RectangleAn actionprint("play soccer")
Diamond after "yes"A condition inside a conditionan indented if inside an if
Python
weather = "sunny"
friends = 11

if weather == "sunny":
    if friends >= 11:
        print("play soccer")
    else:
        print("play badminton")
else:
    print("watch a movie")
Console
play soccer

Practice

1Fill in the blankCurriculum practice

Add a third parameter stage3_time to the function and to the sum, and pass 56.5 when calling it.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
def add_times(stage1_time, stage2_time, ___):
    time = stage1_time + stage2_time + ___
    return time
teamA = add_times(37.5, 62.5, ___)
print(teamA)
Console
Press Run to see the result.
2Write the programCurriculum practice

On the last line print The fastest time is followed by the smallest of teamA, teamB and teamC (use min and str).

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
def add_times(stage1_time, stage2_time, stage3_time):
    time = stage1_time + stage2_time + stage3_time
    return time
teamA = add_times(37.5, 62.5, 56.5)
teamB = add_times(44, 57, 64)
teamC = add_times(42, 63.5, 59)
Console
Press Run to see the result.
3Write the programCurriculum practice

Create a function mul with parameters num1 and num2 that returns their product, then print mul(9, 7).

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
4Write the programCurriculum practice

Create a function good_morning with no arguments that returns the text Good morning, then call it and print the result.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
5Edit the programCurriculum practice

Turn the flowchart into code: inside the first branch, replace the existing line with: if main_ticket equals "fish and chips ticket" print Swap it with a friend, otherwise print Use the steak ticket.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
ticket_type = "main dish"
main_ticket = "fish and chips ticket"
if ticket_type == "main dish":
    print("Check the ticket")
else:
    print("Use the cake ticket")
Console
Press Run to see the result.
6Write the programExtra practice

Museum ticket: anyone under 12 pays 20, a student pays 30, everyone else pays 50. Create a function ticket_price with parameters age and is_student that returns the price, then print ticket_price(10, False), ticket_price(17, True) and ticket_price(30, False) in that order.

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.
7Write the programExtra practice

Create a function count_letter with parameters word and letter that returns how many times the letter appears in the word (use for). Print count_letter("assessment", "s").

Python Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Console
Press Run to see the result.

Key points

  • Several arguments: def f(a, b, c):, passed in the same number and order; none: def f():.
  • A function can contain if and for; return ends it at once.
  • In a flowchart: diamond = if, the "no" branch = else, rectangle = an action.