Functions Exercise
Functions Exercise
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
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.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
Example
This function expects 2 arguments, and gets 2 arguments:
my_function("Emil", "Refsnes")
If you try to call the function with 1 or 3 arguments, you will get an error:
Example
This function expects 2 arguments, but gets only 1:
my_function("Emil")
The return Statement
We return a value from the function using the return statement.
# function definition
def find_square(num):
result = num * num
return result
# function call
square = find_square(3)
print('Square:', square)
Output
Square: 9
Note: The return statement also denotes that the function has ended. Any
code after return is not executed.
Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following 4 types of function arguments.
Default argument
Keyword arguments (named arguments)
Positional arguments
Arbitrary arguments (variable-length arguments *args and
**kwargs)
Let’s discuss each type in detail.
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided
in the function call for that argument. The following example illustrates Default
arguments.
Example 1
# default arguments
print("x: ", x)
print("y: ", y)
# argument)
myFun(10)
Output:
x: 10
y: 50
Example 2
Example 3
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.
Example 1
print(firstname, lastname)
# Keyword arguments
student(firstname='John', lastname='David')
student(lastname='David', firstname='John')
Output:
John David
David John
Example 2
# by keyword arguments
Example 4:
# Arguments in order
fruits(a = 'apple', b = 'banana', p = 'pineapple')
Output –
All the above keyword argument methods will fetch the same output.
print("Case-1:")
nameAge("Suraj", 27)
print("\nCase-2:")
nameAge(27, "Suraj")
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
Using*argsand**kwargsin Functions
We can handle an arbitrary number of arguments using special symbols *args and **kwargs.
*args in Functions
As the name suggests, sometimes the programmer does not know the
number of arguments to be passed into the function. In such cases,
Python arbitrary arguments are used. In this, we use the asterisk (*) to
denote this method before the parameter in the function. This is also
called as Python *args.
Example 1 –
add(3,4,5,6,7)
add(1,2,3,5,6,7,8)
Output –
Sum: 25
Sum: 32
In the above program, the programmer does not know in advance the
number of passing arguments in the function. Hence we have used the
Arbitrary arguments method. The *num accepts all the parameters
passed in the function add() and computes summation for all the values.
Python *args can also print data of various types which is passed into
the function. For example, Information related to a person such as a
Name, Sex, Age, City, Mobile number, etc.
Example 2 –
def Person(*args):
print(args)
Person('Sean', 'Male', 38, 'London', 9375821987)
Output –
Example 3:
Python program to illustrate *args with a first extra argument
Example 4:
# sum of numbers
def add(*args):
s=0
for x in args:
s=s+x
return s
result = add(10,20,30,40)
print (result)
result = add(1,2,3)
print (result)
*kwargs in Functions
Using **kwargs allows the function to accept any number of keyword arguments.
The `**kwargs` syntax allows us to pass a variable number of keyword arguments to
a function.
The arguments are collected into a dictionary, which can be accessed within
the function.
Example 1::
def greet(**kwargs):
print(f"{key}: {value}")
In this example, the `greet` function accepts any number of keyword arguments
using the `**kwargs` syntax. The arguments `”name”: “Alice”,` `”age”: 25`, and
`”city”: “New York”` are collected into a dictionary `kwargs.` We then iterate over the
Example 2:
# function to print keyword arguments
def greet(**words):
for key, value in words.items():
print(f"{key}: {value}")
Python provides some built-in functions that can be directly used in our
program.
import math