Python Functions

There are several built-in functions in python. But you can also write your own function. A function is like a mini-program within a program. To write a function you have to use the def keyword. Here is an example of a function:

Example:

  1. def my_func():
  2. print("This is a Function.")
  3. my_func()

Output:

This is a Function.

The def statement defines a function name my_func(). In the block the code is written which executes when the function is called. The function call is just the name of the function followed by the parentheses. When the program execution calls a function it will jump to the top line in the function and start executing the code there. A major purpose of a function is that you can call a function multiple times in a program.

Example:

  1. def my_func():
  2. print("This is a Function.")
  3. my_func()
  4. my_func()
  5. my_func()

Output:

This is a Function.
This is a Function.
This is a Function.

def Statement with Argument

You can pass arguments in your function between the parentheses.

Example:

  1. def my_func(city):
  2. print("City: " + city)
  3. my_func("London")
  4. my_func("Sydney")
  5. my_func("Dhaka")

Output:

City: London
City: Sydney
City: Dhaka

In the example the argument is city. When 1st time the function is called with the value London, the program execution enters the function and the city variable is set to London. So the 1st output is London as well as the 2nd and 3rd output is Sydney and Dhaka respectively.

You can pass as many arguments as you want. If your function has two parameters you have to pass two arguments during functin call.

Example:

  1. def my_func(city1, city2):
  2. print(city1 + " and " + city2)
  3. my_func("London", "Sydney")

Output:

London and Sydney

If you don't know how many arguments you have to pass in your function then you can use a * before the parameter name.

Example:

  1. def my_func(*cities):
  2. print(cities[1] + " is the capital of australia.")
  3. my_func("London", "Canberra", "New York", "Dhaka")

Output:

Canberra is the capital of australia.