Functions
Functions are code blocks that can be called from other parts of your program. You might want to use a function if you are going to use the same code multiple times or if you want to break down a large program into smaller parts.
We have already seen some functions in the previous chapters, like the built-in print
function.
print("Hello World")
Creating Functions
The def
keyword is used to specify a function followed by the name.
Any arguments that the function takes are defined inside parentheses.
When the function is called, the code block is executed much like an if
statement.
def hello():
print("Hello World")
hello() # Output: Hello World
Arguments
Arguments can be passed to a function by specifying them in parentheses. The arguments are variables that can be used inside the function.
Positional Arguments
Positional arguments are arguments that are passed to the function in the same order as they are defined. Each argument is separated by a comma. You can have any number of positional arguments.
def hello(first, last):
print("Hello", first, last)
hello("john", "doe") # Output: Hello john doe
Exercise
Write a function named add
that takes two arguments and prints their sum.
Function exercise
Keyword Arguments
Keyword arguments are arguments that are passed to the function with a keyword. You can even specify positional arguments using keywords.
def hello(first, last):
print("Hello", first, last)
hello(last="doe", first="john") # Output: Hello john doe
However, keywords are mostly used for optional arguments that have default values. You can also use keywords to specify arguments in a different order than they are defined.
def hello(first, last="doe"):
print("Hello", first, last)
hello("john") # Output: Hello john doe
hello("john", "smith") # Output: Hello john smith
hello(last="deer", first="john") # Output: Hello john deer
hello(first="jim") # Output: Hello jim doe
If you want to only allow positional or keyword arguments you can use the /
and *
symbols
to specify where the positional and keyword arguments start.
def test(position_only, /, position_or_keyword, *, keyword_only):
# code block
The print
function is also a good example of a function that takes arguments.
print("Hello", "World", sep="-", end="!\n") # Output: Hello-World!
The first two arguments are positional arguments and the last two are keyword arguments.
The print
function can take any number of positional arguments, but there are only a few keyword arguments.
Here is what the help
function says about the print
function.
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Keyword arguments can have default values so you don't
have to specify them every time you call the function. For example, the print
function
has a default value for the end
keyword argument which will add a newline character
at the end, but you can override it by passing a different value.
Exercise
Modify the code below to print 0-9 on a single line.
Keyword exercise
Return Values
Functions can produce a value by using the return
keyword. This is useful
for creating a reusable expression that can be used in other parts of your program.
def isPositive(x):
return x > 0
print(isPositive(5)) # Output: True
print(isPositive(-5)) # Output: False
if isPositive(5):
print("Positive")
else:
print("Negative")
Exercise
Write a function named add
that takes two arguments and returns their sum.
Function exercise
Scope
Scope refers to where a variable can be accessed. There are two types of scope: global and local.
Global scope
A variable created outside of a function has a global scope and can be accessed inside or outside of a function.
def print_x():
print(x)
x = 10
print_x() # Output: 10
x = 20
print_x() # Output: 20
Local scope
A variable created inside a function is only available inside that function. This is called the scope of the variable. I variables with the same name can exist inside and outside of a function.
x = 5
def print_x():
x = 10
print(x)
print_x() # Output: 10
print(x) # Output: 5
Global keyword
If you want to modify a global variable inside a function, you can use the global
keyword.
x = 5
def print_x():
global x
x += 1
print(x)
print_x() # Output: 6
print(x) # Output: 6
Exercise
Given a number x
, do the following:
- Create a function called
add_one
that increases the value ofx
by 1. - Create a function called
add_two
that takesx
as an argument and returns the value ofx
plus 2.