What is a Function in Python?

Aldrin Caalim
Probably Programming
2 min readApr 18, 2022

--

Photo by Glen Carrie on Unsplash

What is a Function?

A function is a named block of code that has the ability to perform an action. The structure of a function varies between languages. In order to properly invoke your function, you must terminate a function you’re calling with parenthesis.

def say_hi():
return "Hi"
print(say_hi()) # properly invoked
print(say_hi) # not properly invoked, see what happens

Remember to keep this in mind. In Python, you’ll always receive an output from a function.

def say_hi():
return "Hi"
def say_none():
'I will give you None since I do not use the "return" keyword'
print(say_hi())
print(say_none())

Why would you use a Function?

  • It keeps your code DRY (Don’t Repeat Yourself) — essentially it prevents code duplication. This allows you to create specific tasks in a neatly packaged block of code that we can call whenever you need it.
  • It helps in splitting complex blocks of code into smaller blocks, which helps when you have to debug your code.
  • It makes it easier to trace where bugs may be occurring in your code.
  • It helps with readability of your code.

Passing Arguments into a Function

Functions allow you to pass arguments into them, which make them more customizable.

def say_hi(name):
return "Hi " + name
print(say_hi("Jim"))

Default Arguments

Imagine if there were no arguments passed into your function. What would it return?

def say_hi(name):
return "Hi " + name
print(say_hi()) # returns TypeError

Hint, it’ll return a “TypeError” since, in this case, the function required one argument.

A preventative measure would be to create a default argument.

def say_hi(name="Pam"):
return "Hi " + name
print(say_hi()) # returns "Hi Pam"

--

--