24
Python Basics 102: Introduction to Python Functions.
Hello world, In the previous post i introduced you to Python programming language, a high level language.
In this second post I am going to be taking you through python Functions.
In this second post I am going to be taking you through python Functions.
So, what are functions in python!
Let us define a function:
We use the def keyword to define a function:
We use the def keyword to define a function:
# define a function that says Hi.
def greet():
print("Hello")
#calling the function
greet()
#prints> Hello
🤯 Awesome!
# structure of a function
def function_name(paramters):
"""docstring"""
statement(s)
A python function consists of the following:
def
keyword, marks the beginning of a function """docstring"""
, to explain what the function does.return
(optional) statement that returns a value to the function.Functions takes variables as arguments.
Ways of defining arguments; using default, keyword and arbitrary arguments.
Defining functions with parameters. Parameters are identifiers in the function definition parentheses
Ways of defining arguments; using default, keyword and arbitrary arguments.
Defining functions with parameters. Parameters are identifiers in the function definition parentheses
#function parameters
def greet(name, msg):
print(f"Hello {name}, {msg}")
#call the function with the arguments
greet('Mark', 'Good Evening')
#prints> Hello Mark Good Evening
Here, the function
When the function is called, the two
greet()
has two parameters name, msg
When the function is called, the two
parameters
are passed as arguments
.A function can take a variable number of arguments.
def greetings(name, msg="How are you?"):
print(f"Hello, {name} {msg}")
#positional arguments.
greetings('Asha')
#> Hello, Asha How are you?
Even if we call the function with just one argument, it will complete smoothly without an error unlike in the previous function.
When an argument for
When an argument for
msg
is provided in function call, it will overwrite the default argument.When a function is called with values, they get assigned to their specific positions.
But this can be changed when calling a function, the order can be altered with keywords, like in the above function we could call it like this:
But this can be changed when calling a function, the order can be altered with keywords, like in the above function we could call it like this:
#keyword arguments in order
greetings(name="fast furious", msg="is out!")
#keyword arguments out of order
greetings(msg="is out!", name="Vin")
Well give it a try, everythings works just fine.
At times you might not know the number of arguments to be passed in a function.
In situations like this, python allows the use of an asterisk (*) to denote arguments. example:
In situations like this, python allows the use of an asterisk (*) to denote arguments. example:
def greet(*names):
for name in names:
print(f"Hello {name}.")
greet('juma', 'larry', 'lilian')
#> Hello juma.
#> Hello larry.
#> Hello lilian.
Recusion with python functions.
A repeated procedure can be reffered to as a Recursion.
A recursive function, is a function that calls itself.
A repeated procedure can be reffered to as a Recursion.
A recursive function, is a function that calls itself.
def recurse():
#statements
recurse() #recursive call
recurse()
An example:
#finding the factorial of a number
def factor(x):
"""
this function finds the factorial of a given number
factorial number is the product of a
number starting from 1 to that number itself
"""
if x == 1:
return 1
else:
return (x * factor(x-1))
num = 3
print(f"factorial is: {factor(num)}")
An anonymous function is a function that has no name.
They are also called lambda functions.
Defining a lambda function:
They are also called lambda functions.
Defining a lambda function:
#syntax:
lambda arguments: expression
They can have multiple arguments but only one expression.
working example:
working example:
#sum of numbers
sum = lambda x: x+2
print(sum(2))
#> 2+2= 4
#multiple args
product = lambda x, y: x*y
print(product(2, 6))
#> 2*6 = 12
Lambda functions are used when a nameless function is required for a short period of time.
They are best used with in-built functions, filter() & map().Read more
They are best used with in-built functions, filter() & map().Read more
That's it for now, Hope you enjoyed reading this article.
let us learn python!!
Be cool, Keep coding.
let us learn python!!
Be cool, Keep coding.
24