Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Functions

Python

python logo

In this tutorial we will learn about functions in Python.

What is a function?

A function is a block of code that is written to perform a specific task.

Functions provide better modularity and code reusability.

We can also pass data to functions as arguments. And functions can also return values.

Creating a function

We create functions in Python using the def keyword followed by function name then parenthesis and : colon.

Following is the syntax of a function.

def func():
  #
  # body of the function
  #

Where, func is some function name. The body of the function must be properly indented.

In the following Python program we are creating a greetings function.

# func
def greetings():
    print("Hello World")

Rules to name a function

Remember the following points when naming functions in Python.

  • Function name must start with a letter or underscore _.
  • Can use digits (0-9).
  • Can use lowercase and uppercase letters (a-z A-Z).
  • Function name can be of any length. But prefer giving a logical name and keep it short.
  • Must not use Python keywords to name a function.

Calling a function

To execute the code inside a function body we have to call a function.

We call a function by writing its name followed by parenthesis.

In the following Python program we are creating a greetings function and then calling it.

# func
def greetings():
    print("Hello World")

# call
greetings()

We will get the following output for the above code.

Hello World

Create a function that takes arguments

We can pass some value as an argument to a function.

Syntax:

def func(param):
  #
  # body of the function
  #

# call
func(value)

Where, func is the name of the function. param is a function parameter.

When we are calling the function we are passing value as an argument to the function and the value is assigned to the param which can be used inside the body of the function.

In the following Python program we are creating a greetings function that takes a name and prints a greeting message.

# func
def greetings(name):
    print("Hello %s!" %(name))

# call
greetings("Yusuf")

The above code will give us the following output.

Hello Yusuf!

Note! we are passing a string value "Yusuf" as an argument when calling the greetings function.

The passed value is assigned to the function parameter name.

Inside the function body we are printing the message by using string formatting.

Create a function with default parameter

We can also create a function with parameters having default value. So, if the argument is not passed during function call then the default value is used.

Syntax:

def func(param = val):
  #
  # body of the function
  #

Where, func is the name of the function. param is some parameter which is assigned a default value val.

In the following Python program we are calling the greetings function twice.

In the first call we are passing a string value to the function and hence the function is using that string to print out a greetings message.

In the second call we are not passing any value to the function hence the default value "World" is used to print the greetings message.

# func
def greetings(name = "World"):
    print("Hello %s!" %(name))

# call with value
greetings("Yusuf Shakeel")

# call without value
greetings()

We will get the following output for the above code.

Hello Yusuf Shakeel!
Hello World!

Return value from function

We can return value from a function using the return keyword.

Syntax:

def func():
  return val

Where, func is some function name. val is some value returned by the function.

In the following Python program we are creating a greetings function which will return a greeting message.

# func
def greetings(name = "World"):
    return "Hello %s!" %(name)

# call with value
message = greetings("Yusuf Shakeel")
print(message)

# call without value
message = greetings()
print(message)

The above code will return the following output.

Hello Yusuf Shakeel!
Hello World!

In the first function call we are passing a string value to the function and it is returning back a string message "Hello Yusuf Shakeel!"

In the second function call we are not passing any value to the function and the function is using the default parameter value and returning back the following string "Hello World!".

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT