Python Functions
A function is a named block of code that does one job. You write it once and call it whenever you need that job done. Functions keep programs short, because code is not repeated; they make programs easier to read, because a good name says what a block does; and they make programs easier to fix, because a mistake is corrected in one place. You have already used many built-in functions: print, len, input, sorted.
Defining and calling a function
A function is defined with def, its name, brackets with its parameters, and a colon. The indented block below is the function's body. Defining a function does not run it; calling it does:
def greet(name):
print(f"Hello, {name}! Welcome to Python.")
greet("Asha")
greet("Ravi")Hello, Asha! Welcome to Python. Hello, Ravi! Welcome to Python.
When greet("Asha") is called, the parameter name gets the argument "Asha", and the body runs. The second call runs the same code with another argument.
Returning a value
Most functions work something out and give the result back with return. The caller can store the result, print it or use it in an expression:
def area(width, height):
return width * height
def describe(width, height):
a = area(width, height)
shape = "square" if width == height else "rectangle"
return f"a {shape} of {a} square units"
print(area(3, 4) + area(2, 2))
print(describe(5, 5))
print(describe(2, 7))16 a square of 25 square units a rectangle of 14 square units
return also ends the function immediately. A function can call other functions, as describe calls area.
Functions without return
A function that has no return statement, or a bare return, gives back the special value None:
def show(x):
print("showing", x)
result = show(42)
print(result)showing 42 None
This explains a common mistake: print(show(42)) prints the line and then None. Decide for each function whether it does something (prints, saves) or computes something (returns), and prefer functions that return values: they are easier to test and to reuse.
Naming and documenting
Name functions with verbs in lower case with underscores, such as calculate_total or is_valid_email, and put a docstring as the first line to explain what the function does, what it needs and what it returns.
Practice exercises
- Write a function
square(n)that returnsn * n, and print the squares of 1 to 5 using it. - Write
celsius_to_fahrenheit(c)and use it in a loop over several temperatures. - Write
is_even(n)that returnsTrueorFalse, and use it in anif. - Write
max_of_three(a, b, c)without using the built-inmax.