Python Functions
A function is a block of code that has a name and does one job. It runs only when you call it. Functions help you avoid writing the same code again and again, and they make a program easier to read.
Python has many built-in functions like print() and len(). In this chapter we learn to create our own functions.
Create and call a function
A function is defined with the def keyword, followed by the function name, brackets and a colon. The code inside the function is indented.
def function_name():
statements
Here is a simple function. Remember, defining a function does not run it.
def show_message():
print("Welcome to TutorialsClass")
If you run only this code, nothing is printed. To run the function, call it by its name with brackets.
def show_message():
print("Welcome to TutorialsClass")
show_message()
show_message()
Welcome to TutorialsClass
Welcome to TutorialsClass
We called the function two times, so the message is printed two times. That is the benefit of a function: write once, use many times.
Parameters and arguments
A function can get information from outside. The names written in the brackets of def are parameters, and the real values you pass while calling are arguments.
def greet(name):
print("Hello,", name)
greet("Robin")
greet("Maria")
Hello, Robin
Hello, Maria
More than one parameter
def add(a, b):
print(a + b)
add(10, 20)
30
The number of arguments must match the number of parameters. If you pass fewer or more, Python raises a TypeError.
Keyword arguments
You can pass arguments with the parameter name, so the order does not matter.
def student(name, city):
print(name, "lives in", city)
student(city="Delhi", name="Robin")
Robin lives in Delhi
Default values
A parameter can have a default value. It is used when the caller does not give that argument.
def greet(name, message="Welcome"):
print(message, name)
greet("Robin")
greet("Robin", "Good morning")
Welcome Robin
Good morning Robin
Any number of arguments
Put * before a parameter name to accept many positional arguments as a tuple. Use ** to accept many keyword arguments as a dictionary. Read more in What are *args and **kwargs?
def total(*numbers):
print(sum(numbers))
total(1, 2, 3, 4)
10
The return statement
A function can send a value back to the place where it was called, using return. The function stops as soon as it reaches return.
def get_square(x):
return x * x
result = get_square(3)
print(result)
9
If a function has no return, it returns None automatically.
Return more than one value
Python can return many values separated by commas. They come back as a tuple, and you can unpack them.
def min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_max([4, 9, 1, 7])
print(lowest)
print(highest)
1
9
Does Python pass by value or by reference?
Many beginners ask this. Python passes a reference to the object. What happens depends on whether the object can be changed (mutable) or not.
def change(number, items):
number = number + 10 # makes a new int
items.append(99) # changes the same list
n = 5
my_list = [1, 2]
change(n, my_list)
print(n)
print(my_list)
5
[1, 2, 99]
The integer outside is not changed, because integers are immutable. The list is changed, because the function works on the same list object. See mutable and immutable types.
Docstring
The first line inside a function can be a string that explains it. It is called a docstring.
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add.__doc__)
Return the sum of a and b.
Recursion
When a function calls itself, it is called recursion. Every recursive function needs a base case, which is the condition where it stops. Without it the function calls itself forever and Python raises a RecursionError.
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
120
For factorial(5) Python calculates 5 x 4 x 3 x 2 x 1. Recursion is good for problems like factorial, Fibonacci and folders inside folders. For simple counting a loop is usually easier.
The pass statement
A function cannot be empty. If you want to write it later, use pass as a placeholder.
def future_function():
pass
Summary
- Use
defto create a function and its name with brackets to call it. - Parameters take values from the caller. They can have default values.
- Use keyword arguments when the order is not clear.
returnsends a value back. Many values come back as a tuple.- A function can call itself (recursion), but it needs a base case.
- Next, learn small one-line functions in Python Lambda and the scope of variables.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |