Python Functions

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Python tutorial, let us discuss Python Functions with appropriate examples.

Introduction of Python Functions

A function is a block of code that only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

Creating a function

In Python, a function is defined using the def keyword.

Example

def my_function():

  print("Hello from a function")

Calling a function

To call a function, use the function name followed by a parenthesis.

Example

def my_function():
  print("Hello from a function")
my_function()

Output

Hello from a function

Arguments

Information can be passed into functions as arguments.

They are specified after the function name inside the parenthesis. You can add many arguments as you want, just separate them with a comma.

Example

def my_function(fname):
 print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")

Output

Emil Refsnes
Tobias Refsnes
Linus Refsnes

Arbitrary Arguments, *args

If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.

Example

def my_function(*kids):
  print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")

Output

The youngest child is Linus

Keyword Arguments

You can also send arguments with the key = value syntax.

Example

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Output

The youngest child is Linus

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

If you send a list as an argument, it will still be a List when it reaches the function.

Example

def my_function(food):
  for x in food:
    print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

Output

apple
banana
cherry

Return Values

To let a function return a value, use the return statement.

Example

def my_function(x):
  return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

Output

15
25
45

Leave a Comment

Your email address will not be published. Required fields are marked *