def hello_world():
print("Hello World !")8-Functions
Link to the Google Colaboratory notebook: 8-Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creation
To define a function, one should use the def keyword:
Call a function
To call a function, use the function named followed by parenthesis:
hello_world()Hello World !
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
def square_function(x):
print(x**2)
square_function(2)
square_function(8)
square_function(9)4
64
81
Return
To get access to the output of a function, it should have a return inside.
The return will stop the function and code after it will not be considered.
def square_function(x):
return x**2
y = 2
y_square = square_function(y)
print("2 times y**2", 2*y_square)2 times y**2 8
Number of arguments
By default, a function must be called with the correct number of arguments.
Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
def sum_numbers(x, y):
return x+y
z = sum_numbers(3,4)
# z = sum_numbers(3,4, 5) # it will not work
print(z)7
Default parameter
You can specify a default value for a parameter within the definition of the function.
def show_country(country = "France"):
print("My country is", country)
show_country()
show_country("Spain")My country is France
My country is Spain
Keyword argument
You can specify the order of the argument if needed.
def my_function(a,b,c):
print(a+b+c)
my_function(b=3, a=2, c=5)
my_function(a=2, b=3, c=5)10
10