DEV Community

Cover image for Python Basics 102: Introduction to Python Functions.
billy_dev
billy_dev

Posted on • Edited on

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.

Python Functions

everything we do comprises of a function somewhere.
So, what are functions in python!

  • A function is a block of code that has statements that perform a specified task.
  • They help in breaking down a program when it grows big.
  • Functions minimize the repetition of code, hence they're reusable.

Let us 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
Enter fullscreen mode Exit fullscreen mode

🤯 Awesome!

# structure of a function
def function_name(paramters):
    """docstring"""
    statement(s)
Enter fullscreen mode Exit fullscreen mode

A python function consists of the following:

  • the def keyword, marks the beginning of a function
  • A function name to identify the purpose of the function, Function names follow the same guide rules of pep8 naming conventions.
  • parameters to which values to our functions.
  • A colon (:) to mark the end of a function definition.
  • In the body start with a """docstring""", to explain what the function does.
  • One or more valid python statements that make up the function body.
  • The return(optional) statement that returns a value to the function.

Python Function Arguments

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

#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
Enter fullscreen mode Exit fullscreen mode

Here, the function greet() has two parameters name, msg
When the function is called, the two parameters are passed as arguments.

Variable Function Arguments

A function can take a variable number of arguments.

  • Function Default Arguments
def greetings(name, msg="How are you?"):
    print(f"Hello, {name} {msg}")

#positional arguments.
greetings('Asha')
#> Hello, Asha How are you?
Enter fullscreen mode Exit fullscreen mode

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 msg is provided in function call, it will overwrite the default argument.

Python Keyword Arguments

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:

#keyword arguments in order
greetings(name="fast furious", msg="is out!")

#keyword arguments out of order
greetings(msg="is out!", name="Vin")
Enter fullscreen mode Exit fullscreen mode

Well give it a try, everythings works just fine.

Python Arbitrary Arguments

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:

def greet(*names):

   for name in names:
       print(f"Hello {name}.")

greet('juma', 'larry', 'lilian')
#> Hello juma.
#> Hello larry.
#> Hello lilian.
Enter fullscreen mode Exit fullscreen mode

Python Recursion

Recusion with python functions.
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()
Enter fullscreen mode Exit fullscreen mode

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)}")
Enter fullscreen mode Exit fullscreen mode

Pros of Recursion Functions

  • Makes code look clean and elegant.
  • Breakdown of complex tasks into smaller sub-tasks.
  • Sequencing is easier compared to nested iteration.

Cons

  • They are difficult to debug.
  • Recursive calls take alot of memory and time.
  • Hard to read or follow.

Anonymous Functions

An anonymous function is a function that has no name.
They are also called lambda functions.
Defining a lambda function:

#syntax:
lambda arguments: expression
Enter fullscreen mode Exit fullscreen mode

They can have multiple arguments but only one expression.
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
Enter fullscreen mode Exit fullscreen mode

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

That's it for now, Hope you enjoyed reading this article.
let us learn python!!
Be cool, Keep coding.

Top comments (0)