Functions
Functions let us run a block of code by calling the function's name. A function may or may not get parameters and return values. We can use a single function as many times as we want!
Some advantages of using functions:
- Avoid code duplication
- More readable - functions with self-explanatory names
- Much easier to modify (no code duplication)
- Much easier to debug
Defining a Function
A function is defined using the def keyword. Evry function must have a unique name. The name is followed by parentheses.
The Syntax:
def function_name(parameters):
    Code Block
#Function
def my_func():
print("My very first python function!")
The function in the example above doesn't get any parameters. When we call it, the function prints the same phrase.
Add Arguments
Data can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses and separated by a comma.
#Arguments
def my_func(a, b):
print(a, "comes before", b)
my_func("The chicken", "the egg")
Calling a Function
To call a function, use the function name followed by parenthesis:
#Function
def my_func():
print("My very first python function!")
my_func()
Keyword Arguments
You can send arguments with the key = value syntax. This method is called keyword arguments.
#Function
def my_func(a, b, c):
print(a)
print(b)
print(c)
my_func(c=5, a=3, b=4)
Default Argument Value
You can create a function with default arguments. When calling the function without argument, it uses the default value.
#Default Argument Value
def my_func(a="Hello, World!"):
print(a)
my_func()
my_func("Hello, Python!")
Arbitrary Keyword Arguments
What if we want to use arbitrary number of arguments? Python provides several methods to do so:
Arbitrary Arguments (*args)
If you do not want to predetermine the exact number of arguments the functions gets, add an asterisk
#*args
def my_func(a, b, *args):
print(a)
print(b)
for i in args:
print(i)
my_func(1, 2, 3, 4, 5)
Arbitrary Keyword Arguments (**kwargs)
If you do not want to predetermine the exact number of arguments the functions gets, add two asterisks
#**kwargs
def print_last_name(**kwargs):
for first_name, last_name in kwargs.items():
print("{first_name}'s last name is {last_name}".format(first_name=first_name, last_name=last_name))
print_last_name(Franz="Schubert", Robert="Schumann", Frederic="Chopin")
Exercise
Create a function that prints out your name.
Give it a self-explanatory name.
Call the function a couple of times.
#Write your code here