Functions
A function is a named block of code that you can run as many times as you like. Functions let you break a program into pieces that each do one thing, give those pieces names, and reuse them.
Defining and calling
def greet():
print("Hello from a function")
greet()
greet()def starts the definition, the name is followed by parentheses and a colon, and the body is indented. Defining a function does not run it; calling it with () does.
Parameters
Values passed into a function are called arguments; the names that receive them are parameters.
def greet(name):
print(f"Hello, {name}")
greet("Sana")
greet("Vikram")Multiple parameters are separated by commas:
def area(width, height):
print(width * height)
area(4, 5)Return values
return sends a value back to the caller and ends the function.
def area(width, height):
return width * height
room = area(4, 5)
print(room)
print(area(2, 3) + area(1, 1))A function without a return, or with a bare return, gives back None.
def nothing():
pass
print(nothing())Returning several values
Separate them with commas; the caller receives a tuple and can unpack it.
def stats(values):
return min(values), max(values), sum(values) / len(values)
low, high, mean = stats([4, 8, 15, 16])
print(low, high, mean)Docstrings
Describe what the function does in a string right after the def line.
def celsius_to_f(c):
"""Convert a temperature from Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(celsius_to_f(37))
print(celsius_to_f.__doc__)Functions calling functions
def square(n):
return n * n
def sum_of_squares(a, b):
return square(a) + square(b)
print(sum_of_squares(3, 4))Functions are values
A function can be stored in a variable, put in a list or passed to another function.
def shout(text):
return text.upper() + "!"
def whisper(text):
return text.lower() + "..."
for style in (shout, whisper):
print(style("Hello"))Why write functions
- Avoid repetition. Fix a bug once instead of in five copies.
- Name your logic.
is_valid_email(x)says more than ten lines of checks. - Test in isolation. A small function is easy to try in the shell.
- Limit scope. Variables inside a function do not leak out (see the Scope lesson).
Practice
- Write
is_even(n)that returnsTrueorFalse, and use it in a loop from 1 to 10. - Write
grade(marks)that returns "A", "B", "C" or "F" and call it with a few values. - Write
word_count(sentence)that returns the number of words, then use it on two different sentences.
