Definition
Defining your first function in Python
Parameters in Python
Positional Arguments
Keyword Arguments
Default Arguments
Variable Length Positional Arguments
Variable Length Keyword Arguments
Variable Scope
Lambda Expressions
Summary
Functions enable you to create reusable blocks of code. They create modularity (separate code blocks that perform specific functions) in your code and enable your code to stay organized.
Functions facilitate code reusability. In simple terms, when you want to do something repeatedly, you can define that something as a function and call that function whenever you need to.
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.
Functions are used to utilize code in more than one place in a program. It is also called method or procedure.
Python provides many inbuilt functions like print()
, input()
, len()
, etc. but it also gives freedom to create your own functions.
Python allows you to come up with your own functions.
In Python a function is defined using the def
keyword:
def
function_name(params
):
function body
return
result
This follows the same notation as we have been using for both conditional statement and loops as above in that you need the colon and indentation.
You need to use the def
keyword, give your function a name, followed by a pair of parentheses, and end the line with a colon (:
)
If your function takes arguments, the names of the arguments (parameters) are mentioned inside the opening and closing parentheses.
Please note that in function definition, the arguments that your function consumes are referred to as parameters.
When you call the function with specific values for these parameters, they're called arguments or actual parameters. This is because the arguments in the function call are the values used for the function's parameters.
Then, you begin an indented block. This is the body of the function that describes what your function does.
There's a return
statement that returns the result of the operation on the arguments. The return
statement returns control to the point where the function was originally called.
Note : The arguments and the return statement are optional. This means that you could have a function that takes in no arguments, and returns nothing. 😀
# example 1
def my_example():
print("Hello from a function!")
The above example, the function my_example
:
Takes no arguments
Returns nothing
Prints out "Hello from a function!" Every time the function is called
Let's go ahead and call the function my_example()
and check the output.
# call the function
my_example()
Hello from a function!
Both a function definition and a function call must always include parentheses, even if they’re empty.
Occasionally, you may want to define an empty function that does nothing. This is referred to as a stub, which is usually a temporary placeholder for a Python function that will be fully implemented at a later time.
Just as a block in a control structure can’t be empty, neither can the body of a function.
To define a stub function, use the pass
keyword.
def my_func():
# code will be added later
pass
The arguments are types of information that can be passed into the function. The arguments are specified in the parentheses. We can pass any number of arguments to the functions, but we have to separate all the arguments with the help of a comma.
modify the function my_example()
to include the name and city of the user.
# example 3
def my_example(name, city):
print("Hello, ",name)
print("How is ", city)
my_example("John","Cape Town")
Hello, John How is Cape Town
What happens if you specify the city first and then the name? Let's find out.
# example 4
def my_example(name, city):
print("Hello, ",name)
print("How is ", city)
my_example("Cape Town","John")
Hello, Cape Town How is John
We get Hello, Cape Town How is John – and this doesn't make sense.
The arguments in the function call are positional arguments. This means that the first argument in the function call is used as the value of the first parameter (name) and the second argument in the function call is used as the value of the second parameter ( city )
The most straightforward way to pass arguments to a Python function is with positional arguments (also called required arguments). In the function definition, you specify a comma-separated list of parameters inside the parentheses.
See the code snippet below. Instead of specifying only the arguments, we've mentioned the parameters and the values they take.
# example 5
def my_example(name, city):
print("Hello, ",name)
print("How is ", city)
my_example(city="Cape Town", name="John")
Hello, John How is Cape Town
These are called keyword arguments. The order of arguments in the function call does not matter so long as the names of the parameters are correct.
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
# example 6
def my_example(name, city="Paris"):
print("Hello, ",name)
print("How is ", city)
my_example("John")
Hello, John How is Paris
# example 7
def my_example(name="Jane", city="Paris"):
print("Hello, ",name)
print("How is ", city)
my_example()
Hello, Jane How is Paris
# example 8
def my_example(name="Jane", city="Paris"):
print("Hello, ",name)
print("How is ", city)
my_example("Steve", "Ottawa")
Hello, Steve How is Ottawa
let's create a simple function that returns the volume of a cuboid given the length
, the width
, and the height
.
# example 9
def volume_cuboid(length, width, height):
volume = length * width * height
return volume
cuboid1 = volume_cuboid(10,10,10)
print("Volume of our cuboid is ", cuboid1, "cm cubed")
Volume of our cuboid is 1000 cm cubed
A return
statement in a Python function serves two purposes:
It immediately terminates the function and passes execution control back to the caller.
It provides a mechanism by which the function can pass data back to the caller.
use function_name(*args)
for an unknown number of positional arguments.
This is used when we don’t know the exact number of arguments we would pass but need to process them in a similar manner.
For instance, you want to write a function for calculating total amount of sales given prices of good bought. You don’t know in advance how many goods you are going to sum. This comes in handy in cases like this:
# example 10
def sum_goods(*args):
total = 0; # initialize variable
for num in args:
if isinstance(num, int):
total += num
return total
budget1 = sum_goods(20,50,60)
print(budget1)
budget2 = sum_goods(20,50,60,70,90,60)
print(budget2)
130 350
When you use the *
syntax, the args is basically a tuple of values of all the positional arguments.
args name is optional, but be sure to include the *
for unpacking the arguments.
Use function_name(**kwargs)
for an unknown number of keyword arguments.
We use this to pass an arbitrary number of keyword arguments and the function will receive those as a dictionary, from which we can extract the values we want
# example 11
def save_info(**kwargs):
if kwargs:
for key, val in kwargs.items():
print(key,"--> ", val)
save_info(name="ken",email="myemail@email.com", age=42)
name --> ken email --> myemail@email.com age --> 42
person_info = {"name":"John", "city":"New York", "status":"active"}
save_info(**person_info) # pass in a dictionary like this
name --> John city --> New York status --> active
Leveraging *args
and **kwargs
can be really useful when you have tons of parameters and don’t expect the user to pass each one on every function call.
Or, it also can be applied when you don’t know how many parameters the user will be passing in.
A variable is only available from inside the region it is created. This is called scope.
Scope rules how variables and names are looked up in your code. It determines the visibility of a variable within the code. The scope of a name or variable depends on the place in your code where you create that variable. The Python scope concept is generally presented using a rule known as the LEGB rule.
The letters in the acronym LEGB stand for Local, Enclosing, Global, and Built-in scopes.
A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Some examples:
# example 12
# define a varialbe person
person = "Jane"
# define a function
def greet_person(name):
person = name
print("hello", person)
greet_person("James")
print(person) # does not change value of global variable
hello James Jane
# example 13
# define a varialbe person
person = "Jane"
# define a function
def greet_person(name):
global person
person = name
print("hello", person)
greet_person("James")
print(person) # change value of global variable
hello James James
Note: Using the
global
keyword is bad practice and you should avoid it.
# example 14
x = lambda a, b : a * b
product = x(5,10)
print(product)
50
Notice that in the definition of the lambdas, the arguments don’t have parentheses around them. Multi-argument functions (functions that take more than one argument) are expressed in Python lambdas by listing arguments and separating them with a comma (,) but without surrounding them with parentheses
# example 15
full_name = lambda first, last: f'Full name: {first.title()} {last.title()}'
guido = full_name('guido', 'van rossum')
print(guido)
Full name: Guido Van Rossum
def multiply(input_list):
product = 1 # initialize variable
for num in input_list:
if isinstance(num, int) or isinstance(num, float):
product *= num
else:
print("Non Numeric Input")
return product
sample_input = [8, 2, 3, -1, 7]
sample_output = multiply(sample_input)
print(sample_output)
-336
Sample Input : 'The quick Brow Fox'
Output :
Uppercase Letters: 3
Lowercase Letters: 12
def count_chars(input_str):
# initialize count variables
upper_count = 0
lower_count = 0
# loop through each element of the string
for char in input_str:
# check if char is an alphabet since our string might contain spaces and special characters
if char.isalpha():
# check if char is lowercase
if char.islower():
lower_count += 1
else:
# if it is not lower case it has to be upper case
upper_count += 1
return f" Uppercase Letters: {upper_count}\n Lowercase Letters: {lower_count}"
sample_input = "The quick Brown Fox"
sample_output = count_chars(sample_input)
print(sample_output)
Uppercase Letters: 3 Lowercase Letters: 13
## Your Solution here
##
As applications grow larger, it becomes increasingly important to modularize code by breaking it up into smaller functions of manageable size. Functions enable you to reduce the amount of code that you actually produce.
An important acronmy in coding is DRY
Don't
Repeat
Yourself
Which means you shouldn't be creating the same code over an over again as why would you want to!
A function does then by creating a block of code that runs when the function itself when it is called. You can pass data, known as parameters, to the function and it can return data as a result