Functions
Basics10 min readLesson 8 of 8
A function is a named block of code that you can call whenever you need it. You give input through parameters, and the function can send a result back with return. A short function that does one clear job is easier to test and reuse than the same lines copied through a program. A function with no parameters is still called with parentheses.
def greet(name):
message = 'Hello, ' + name
print(message)
greet('Asha')Output
Hello, Asha
8.1 Defining and calling
def starts the definition, then the function name, parentheses, and a colon. The indented body runs when you call the function by name. The names in the definition are parameters; the values you pass in the call are arguments. A return statement ends the function immediately and sends a value back to the caller. The caller can store that value, print it, or use it in another expression.
def add(a, b):
return a + b
result = add(3, 4)
print(result * 2)Output
14
8.2 Common mistake
A function that uses print() has shown the value and returned nothing. print() displays something; return sends a value back to the caller. A function with no return statement gives back None, even when it printed helpful text. If the caller stores that value and adds a number, Python raises TypeError. Return the value when you want to use it later, and print when seeing the text is enough.
def greet(name, greeting='Hello'):
return f'{greeting}, {name}!'
print(greet('Ravi'))
print(greet('Mira', 'Good morning'))Output
Hello, Ravi! Good morning, Mira!
8.3 Defaults and local names
- Default values are assigned when the function is defined, so they suit settings that usually stay the same.
- Parameters without defaults must come before parameters with defaults.
- Callers can override a default by passing a value in the matching position, or by naming the parameter, as in
greet('Mira', greeting='Hi').
A name assigned inside a function is local and exists only while the function runs, so the same name outside the function keeps its own value.
score = 10
def show():
score = 3
print(score)
show()
print(score)Output
3 10
8.4 Practice
- Write
area(length, width)that returns the area of a rectangle, then print the result outside the function. - Give
widtha default value and call the function with one argument and with two. - Add a local variable named
labelinside the function and a differentlabeloutside it, then print both.
