Lesson 6 of 14 · 8 min

Functions

A function is a named recipe. Define it once with def, then call it whenever you need it:

def square(n):
    return n * n

print(square(4))    # 16
print(square(10))   # 100
  • def starts the definition; the body is indented.
  • n is a parameter: a placeholder for the value passed in.
  • return sends the result back and ends the function.

Functions can take several parameters, and give them default values:

def describe(name, job="student"):
    return f"{name} is a {job}"

describe("Ana")               # "Ana is a student"
describe("Tino", "teacher")   # "Tino is a teacher"

return is not print

print only shows a value. return gives it back so your program can store it, compare it or pass it on. A function without return gives back None. The checks for this lesson call your functions and look at what they return.

Your task

Write three functions:

  1. greet(name) returns Hello, <name>!
  2. celsius_to_fahrenheit(c) returns the temperature in Fahrenheit (c * 9 / 5 + 32).
  3. largest(a, b, c) returns the biggest of three numbers, using if statements (not max).
main.py
def greet(name):
    pass  # replace pass with your code


def celsius_to_fahrenheit(c):
    pass


def largest(a, b, c):
    pass


print(greet("Rudo"))
print(celsius_to_fahrenheit(30))
print(largest(3, 9, 4))

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…