Pythonintermediate 8 min
Name and reuse blocks of code with parameters, default values and return.
How to define a function with def, pass values in, get a value out with return, and use default and keyword arguments.
Functions stop you repeating yourself. You write the steps once, give them a name, and use that name whenever you need them. They are also how large programs are broken into understandable pieces.
A function is a named block of code. You create it with def, and run it by calling its name with brackets.
name is a parameter: a placeholder. The value you pass when calling is an argument.return sends a result back and ends the function. Without return, the function gives back None.def greet(name="friend") is used when no argument is given.greet(name="Asha"), so order does not matter.area(4, 5) multiplies 4 by 5 and returns 20.area(7) uses the default height=1, so it returns 7.describe(age=30, name="Asha") uses keyword arguments, so the order does not matter: Asha is 30 years old.stats returns three values at once. Python packs them into a tuple, and we unpack them into low, high, total: 3 9 16.Write a function is_even(n) that returns True when n is even, then print is_even(10) and is_even(7).
return and getting None.greet is the function, greet("Asha") runs it.def add(item, items=[]). The same list is shared between calls. Use None instead.def name(params): defines a function; return sends back a value.Next: Python's built-in collections.
def greet(name):
return "Hello, " + namedef area(width, height=1):
"""Return the area of a rectangle."""
return width * height
def describe(name, age):
return f"{name} is {age} years old"
print(area(4, 5))
print(area(7))
print(describe(age=30, name="Asha"))
def stats(numbers):
return min(numbers), max(numbers), sum(numbers)
low, high, total = stats([3, 9, 4])
print(low, high, total)