Functions: parameters, return values and scope
Write reusable functions with parameters, return values, default arguments, docstrings, *args and lambda, and understand scope.
In this lesson you will
- Define and call functions
- Use parameters, defaults and return
- Understand scope
- Write small, single-purpose functions
About 20 minutes
Teach Python a new word
You have a recipe for tea that you make ten times a day. Each time you do not re-read the steps; you just say “make tea”. A function works the same way: write the steps once, give them a name, then call the name whenever you need them. Functions make programs shorter, easier to fix, and far easier to understand. You have used functions since lesson one: print(), len(), input() are all functions somebody else wrote. Now you will write your own.
Defining and calling a function
def greet():
print("Hello there!")
greet()
greet()
Hello there!
Hello there!
Writing the function does nothing by itself. It is only the recipe. The code runs when you call it by writing its name with brackets. Notice the same rules you know: a colon at the end of the line, and an indented block.
Parameters and arguments
def greet(name):
print(f"Hello, {name}!")
greet("Sara")
greet("Ali")
def add(a, b):
print(a + b)
add(3, 4)
Hello, Sara!
Hello, Ali!
7
Returning a value
Printing is useful for testing, but real functions usually return an answer to whoever called them, so the answer can be stored or used in more calculations.
def add(a, b):
return a + b
total = add(3, 4)
print(total)
print(add(10, 5) * 2)
def is_adult(age):
return age >= 18
print(is_adult(12), is_adult(30))
7
30
False True
When Python reaches return, the function ends immediately. Lines after it inside the function never run. A function with no return gives back None.
Printing instead of returning. A function that only does print(a + b) shows the answer but gives you nothing to use afterwards: x = add(1, 2) would leave x as None. Return the value, and print it outside when you need to see it.
Default values and keyword arguments
def welcome(name="friend", greeting="Welcome"):
return f"{greeting}, {name}!"
print(welcome())
print(welcome("Sara"))
print(welcome(greeting="Salaam", name="Ali")) # by name, in any order
Welcome, friend!
Welcome, Sara!
Salaam, Ali!
Returning several values
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, average = stats([4, 8, 15, 16, 23, 42])
print(low, high, round(average, 1))
4 42 18.0
Docstrings: describing your function
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area(4, 5))
help(area)
20
Help on function area in module __main__:
area(width, height)
Return the area of a rectangle.
Scope: where a variable lives
site = "Skills in Minutes" # global: visible everywhere
def show():
message = "Hi" # local: exists only inside show()
print(message, site)
show()
# print(message) # NameError: it does not exist out here
Hi Skills in Minutes
Variables created inside a function exist only inside it. That is a good thing: functions cannot accidentally break each other’s variables. If you need a value from inside, return it. Avoid the global keyword; it makes code hard to follow.
Functions calling functions
def add_tax(price, rate=0.17):
return price * (1 + rate)
def apply_discount(price, percent):
return price - price * percent / 100
def money(amount):
return f"Rs {amount:,.2f}"
def final_price(price, discount):
return money(add_tax(apply_discount(price, discount)))
print(final_price(1000, 20))
Rs 936.00
Read final_price from the inside out: discount, then tax, then format as money. Because every helper is tiny and clearly named, the code explains itself, and you can reuse money everywhere. Good functions are small and do one thing.
*args and **kwargs: flexible arguments
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4))
def describe(**details):
for key, value in details.items():
print(f"{key} = {value}")
describe(name="Sara", age=28)
10
name = Sara
age = 28
lambda: tiny one-line functions
square = lambda n: n * n
print(square(6))
words = ["banana", "kiwi", "apple"]
print(sorted(words, key=lambda w: len(w)))
people = [("Sara", 28), ("Ali", 22)]
print(sorted(people, key=lambda p: p[1]))
36
['kiwi', 'apple', 'banana']
[('Ali', 22), ('Sara', 28)]
Recursion: a function that calls itself
def factorial(n):
if n <= 1:
return 1 # the stopping point
return n * factorial(n - 1)
print(factorial(5)) # 5 * 4 * 3 * 2 * 1
120
Every recursive function needs a stopping condition, otherwise it calls itself forever. For most beginner tasks a loop is simpler, but recursion is elegant for naturally nested problems.
Write a function celsius_to_fahrenheit(c) that returns the converted value (multiply by 9/5, then add 32). Print the result for 0, 37 and 100.
Show one possible answer
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
for c in (0, 37, 100):
print(c, "C =", celsius_to_fahrenheit(c), "F")
0 C = 32.0 F
37 C = 98.6 F
100 C = 212.0 F
Write is_palindrome(text) that returns True when the text reads the same forwards and backwards, ignoring capitals and spaces. Test it on “Never odd or even”.
Hint: A reversed string is text[::-1].
Show one possible answer
def is_palindrome(text):
cleaned = text.replace(" ", "").lower()
return cleaned == cleaned[::-1]
print(is_palindrome("Never odd or even"))
print(is_palindrome("Python"))
True
False
calculate_total, is_valid_email, get_user_name. A good name makes the call read like a sentence and removes the need for a comment.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Which keyword defines a function?
functionfuncdefinedef
Python uses def.
What does a function return if it has no return statement?
- 0
- None
- An error
- An empty string
It returns None.
What is the difference between a parameter and an argument?
- There is none
- Arguments are in the definition
- A parameter is in the definition; an argument is the value passed in
- Parameters are numbers
Parameters are slots; arguments fill them.
Where can a variable created inside a function be used?
- Only inside that function
- Everywhere
- Only in loops
- In other files automatically
Local variables stay inside.
What is a docstring?
- A kind of loop
- A variable
- A string describing what a function does
- A comment symbol
It is the first string inside the function.
Summary
- def creates a function; return hands back a result.
- Default values and keyword arguments add flexibility.
- Variables inside a function stay inside.
- Small functions with one job are easiest to reuse.
Questions
When should I write a function?
When you repeat the same steps, or when a block of code deserves a clear name.
What is the difference between print and return?
print shows a value on screen. return gives a value back to the caller so it can be used further.
Is a lambda better than def?
Only for tiny throwaway functions, like a sort key. Use def for anything you name or reuse.
