Functions in Python - How it works ?

Python functions are groups of related statements that perform specific tasks. They allow us to repeat statements that are used multiple times in a modular, easy to read format. This is why they allow us to create modular code that provides helpful, descriptive chunks of working with our program.

There are two kinds of functions, one which returns values while others only display output on the screen.

Here at LinuxAPT, we shall look into functions in Python and how they work.

Elements of a function

A function consists of three elements:

  • Function Name.
  • Parameters.
  • A return value.

1. Function Name

Each function has a specific name. For naming a function in python we need to follow these naming conventions.

Naming conventions for function:

  • It can begin with A – Z, a – z, and underscore (_).
  • A – Z, a – z, digits (0 – 9), and underscore (_) can be part of it.
  • A reserved keyword cannot be a function name.

2. Parameters

After the function name, we write parenthesis. In parenthesis, parameters are placed. Our function can have no parameter, or it can have one or more parameters. Parameters are values on which a function performs an operation and they are provided by a user. If we have more than one parameter, then insert a comma to separate them.

Syntax of the function definition:

To define a function, we write keyword def then function name followed by a parenthesis with or without parameters inside and semicolon. All statements that are part of the function body should be indented:

def functionname():

Below is your function definition.

How to Make a Function Call ?

Once you have completed the function definition, now it’s time to call the function. You call the function by its name with the argument list. You need to pass a value for every parameter, otherwise, the default value for that parameter will be considered:

def functionname():

Below is your function definition:


Types of Functions

Based on parameters, we categorize functions as follows:

  • Function without parameters.
  • Function with parameters.

a. Function without parameters

A function that does not have any parameter. Below are a few examples.

i. Take a look at the below function:

def func():
print('Hello i am a function without parameters')

The Output is going to produce:

Hello I am a function without parameters

The body of function has a print statement. Calling the function displays a statement on the screen.

ii. Another example is given below:

def show_main_menu():
"1.Biology\n" +
"2.Pyhsics\n" +
"3.Chemistry\n" +
choice = input("Enter your choice: ")
if choice == "1":
print("You chose Biology")
elif choice == "2":
print("You chose Physics")
elif choice == "3":
print("You chose Chemistry")
elif choice == "4":
print("Wrong choice, Please Enter [1 to 4]\n")
ent = input("Press Enter to continue ...")

The Output will give:

Enter your choice: 2

We choose Physics.

Here, the function displays a menu of options using the print command. For user choice, we have used the input function. The user selects a category number and the program prints a message according to the selected category.

b. Function with parameters

1. Now, take a look at the below example:

def table(num):
for i in range(1,11):

The Output will give:

12 X 1 = 12
12 X 2 = 24
12 X 3 = 36
12 X 4 = 48
12 X 5 = 60
12 X 6 = 72
12 X 7 = 84
12 X 8 = 96
12 X 9 = 108
12 X 10 = 120

Here, we have used for loop to increment the value of 'i'. By calling the function table (12) we get a table of 12.

2. Another example is:

def caldisc(amount):
if amount > 0:
if amount >= 100 or amount <= 199.99:
disc = amount * 0.05
owed = amount - disc
print("value of good {} discount given {} amount owed {}".format(amount, disc, owed))
elif amount >= 200:
disc = amount * 0.10
owed = amount - disc
print("value of good {} discount given {} amount owed {}".format(amount, disc, owed))
print("Invalid Amount")

The Output will give:

value of good 150 discount given 7.5 amount owed 142.5

Here, we have defined a function caldisc(amount) to calculate the values of goods purchased. If the value is £200 or more, a 10% discount is given and if the value is between £100 and £199.99, a 5% discount is given. A discount is subtracted from the value to find the amount owed. Then we have printed the value of goods, discount given and amount owed.

3. Another example is:

def sum_numbers(x,y):
print('sum of two numbers', x,'and', y, 'is', x+y)

The Output will give:

sum of two numbers 12 and 22 is 34

Here, we have defined sum_numbers(x,y) function. It adds two numbers and displays the value.

3. The return statement

The return statement is used to exit a function and go back to the place from where it was called.

The Syntax of return is:

return [expression_list]

This statement can contain an expression that gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.

For example:

>>> print(greet("May"))
Hello, May. Good morning!

Here, None is the returned value since greet() directly prints the name and no return statement is used.

Example of return

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""
    if num >= 0:
        return num
        return -num

Run Code



[Need help in fixing Python function issues ? We can help you. ]

This article covers Python functions which display values on the screen. In fact, The function is a block of related statements that performs a specific task when it is called. Functions helps in breaking our program into smaller and modular chunks which makes our program more organized and manageable. Also, it avoids repetition and makes the code reusable.

Related Posts