Python Functions

In this tutorial you will learn:

  • Functions in Python
  • Function call
  • Passing parameters to functions
  • Returning values from a function
  • Pass by value and by reference

Functions in Python

Functions, one of the most fundamental concepts in programming. Functions help us in modularizing our code it means that we put the most commonly used code in a function block and now we don’t need to write that code again. We can simply call the function again wherever it is required. We can even call a function in a for loop, one good example would be to call a function that gives us a sum for a series of numbers. Some functions that we have been using are called built in functions, these are provided by the programming language e.g the most commonly used print function. Here is how we can define a function.

  1. print("Output Result")
  2. def myFunction():
  3. print("I love Python")

Function call

When we create a function we need to call it anywhere in our code and that can be done with a simple syntax defined in the example.


myFunction() #It’s as simple as that

So every time we call this function Python it will print(“I love Python”). If we call it in a for loop 3 times it will print this function 3 times.

  1. print("\nPrinting I love Python 3 times")
  2. for i in range(3):
  3. myFunction()

Passing parameters to functions

We can pass values to a function from our code as well. Suppose we need a function to combine two words so we can use the code used in the example below

  1. print("\nCombining two words")
  2. def combine(a,b):
  3. print(a," ",b)
  4. combine("Hello", "Python")

Returning values from a Function

Functions can also return values for example result of a computation. Suppose we need to find sum of two numbers or square of two functions then we can pass the numbers and return the output result from the function.

  1. print("\nSumming and Squaring numbers")
  2. def sum(a, b):
  3. return a + b
  4. print("Sum of 10 and 20 is : ", sum(10, 20))
  5. def square(a):
  6. return a*a
  7. for i in range(10):
  8. print(square(i))

Add new comment