← Python from Scratch Lesson 43 of 78 · 10 XP

Functions

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A function is a named piece of code that you can call many times. It is declared with the word def:

def greet(name):          # name is a parameter
    print("Hello,", name)

greet("Anya")             # "Anya" is an argument
greet("Borya")

For a function to return a result, you use return. After return the function ends immediately:

def square(x):
    return x * x

y = square(4) + 1     # 17

The difference between print and return is very important. print shows a value to a person, while return hands it to the program: the result can be stored and used further. A function without return returns None.

Why have functions at all:

  • so you don't repeat the same code;
  • to give a piece of logic a clear name;
  • to check parts of a program separately — the way the tests on this platform do.

Task. Write a function max3(a, b, c) that returns the largest of three numbers. Don't use the built-in max.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.