Python Functions Tutorial

Python Functions Tutorial

Last updated on 26th Sep 2020, Blog, Tutorials

About author

Aravind (Sr Technical Project Manager )

High level Domain Expert in TOP MNCs with 8+ Years of Experience. Also, Handled Around 16+ Projects and Shared his Knowledge by Writing these Blogs for us.

(5.0) | 16325 Ratings 957

In today’s fast-paced IT world, it is always an advantage to have an edge over the others in terms of in-depth knowledge of a certain technology. Python is a widely used language and provides ‘n’ number of opportunities to enthusiastic learners.

In this Python functions post, the goal is to get you the expertise required to get started and work with functions using Python.

Why We Need Python Functions?

Functions manage the inputs and outputs in computer programs. Programming languages are designed to work on data and functions are an effective way to manage and transform this data.

The modifications are generally done to drive outcomes like performing tasks and finding results. And, the set of operations or instructions required to do so comes from logically functional blocks of code that can be reused independently from the main program.

In fact, the main code is also a function, just a very important one. Every other function is logically aligned and maintained to functionally execute from your main code. But, if the function has not been defined, you’ll just have to define one yourself before using it. This is because the definition lists the steps of its operation.

 logically-aligned-and-maintained

Would you rather write a single piece of code 10 times or just once and use it 10 times?

So, functions are nothing but tasks that a user wants to perform. But, defining it once with a name will let you reuse that functionality without making your main programs look too scary. This drastically reduces lines of code and even makes debugging easier.

We’ll be getting into that shortly, but the first reason behind why we use functions is because of their reusability. The fact that even complex operations could be put together as singular tasks that would run with just a call by its name is what has made code today so much clearer as well.

Every programming language lets you create and use these functions to perform various tasks with just a call. And, you could call it any number of times without having to worry about logically structuring its code into your main code every single time.

repeat-your-self-functions

Say, you have a television that stores many channels on it, receives their digital radio broadcasts, converts them into what we watch, while also giving us additional options for a variety of other features as well.

But that doesn’t mean there is someone logically scripting the lines of codes for what you watch every time you turn on your tv or flip a channel. Rather, functions for each task have been logically defined once and keep getting reused time and again according to the features you try to use.

All of this happens by calling different functions as many times as needed from the main function that is running. So, even if you’re turning the volume up or down, its defined function is being called repeatedly.

And, having a system operating the main code to keep calling these functions as and when needed has also made designing and innovating upon it easier.

The important thing to note is that whenever this function is called, it executes its tasks depending on the instructions specified in it.

Subscribe For Free Demo

Error: Contact form not found.

That’s why machines can have different functions. A calculator is probably the most common example of this. It has provisions for addition, subtraction, multiplication, division, and other functions. All its functions have been clearly predefined into it, but it only performs those that you choose to call by pressing a respective button.

Programmers reduce coding time and debugging time, thereby reducing overall development time, by using functions.

Next up on this Python functions post, let’s look at what Python functions actually are.

What Are Python Functions?

The functions in Python are a classic example of the reusability discussed above. So, to serve a wide range of applications from GUI and mathematical computing to web development and testing, Python’s interpreter already comes equipped with numerous functions that are always available for use. And, you could also bring in other libraries or modules to your program that contain pre-defined functions readily available for use.

All you’ll really have to do is download required packages.

So, once defined, a function can be used any number of times at any point in any of your code. Now, this is because Python falls in-line with the DRY principle of software engineering, which aims to replace any repetition of software patterns or codes with abstractions to avoid redundancy and ensure that they can be used freely without revealing any inner details of their implementation.

DRY stands for Don’t Repeat Yourself and this concept of having reusable blocks of codes is very crucial for achieving abstraction in Python. Thus, in order to use a function, all that you’ll really need is its name, its purpose, its arguments (if it takes any), and its result’s type (if it returns any).

It’s almost like using an automobile or a telephone, where you don’t necessarily need to understand the working of its components to use them. Rather, they’ve been built to serve common purposes that you can just use directly to achieve your goals and devote your precious time to implementing all the innovative aspects of your application.

A function can be called as a section of a program that is written once and can be executed whenever required in the program, thus giving us code reusability.

The function is a subprogram that works on data and produces some output.

To define a Python function, you’d have to use the def keyword before the name of your function and add parentheses to the end, followed by a colon.

Python uses indentation to indicate blocks, instead of brackets, to make code more readable.

A function in Python may contain any number of parameters or none. So, when you need your function to operate on variables from other blocks of code or from your main program, it could take any number of parameters and produce results.

A Python function could also optionally return a value. This value could be a result produced from your function’s execution or even be an expression or value that you specify after the keyword ‘return.’ And, after a return statement is executed, the program flow goes back to the state next to your function call and gets executed from there.

So, to call a Python function at any place in your code, you’ll only have to use its name and pass arguments in its parentheses, if any.

The rules for naming a function are the same as naming a variable. It begins with either letter from A-Z, a-z in both upper and lower cases or an underscore(_). The rest of its name can contain underscores(_), digits(0-9), and any letters in upper or lower case.

    1. 1.A reserved keyword may not be chosen as an identifier.
    2. 2.Good usage of grammar to ensure enhanced readability of code.

It is good practice to name a Python function according to what it does. 

Next up in this Python functions post, let us check out the types of functions available in Python.

Calling a Function

Once the structure of a function is finalized, you can execute it by calling the function using the function name.

Example:

  • def my_function():
  • print(“Hello Python”)
  • my_function()
  • Python – calling function

Output:

  • Hello Python
  • calling_function_output
  • Calling a Function using Parameters

We can define any number of parameters while defining a function.

Syntax:

  • def my_function(parameters): 
  • #Block of code or statements

Example:

  • def my_function(fname):
  • print(“Current language is: “, fname)
  • my_function(“Python”)
  • my_function(“Java”)
  • Python – calling function with parameters

Output:

  • Current language is: Python
  • Current language is: Java
  • Python – calling function with parameters – output
  • Return Statement

A return statement is used to return a value from the function.

Example:

  • def additions(a, b):
  • sum = a+b
  • return sum
  • print(“Sum is: “, additions(2, 3))

Output:

Sum is: 5

Python – return statement

Output:

  • Python – return statement – output
  • Function Arguments

In python, we can call a function using 4 types of arguments:

  • Required argument
  • Keyworded argument
  • Default argument
  • Variable length arguments

1.Required Arguments:

Required arguments are the arguments which are passed to a function in a sequential order, the number of arguments defined in a function should match with the function definition.

Example:

  • def addition(a, b):
  • sum = a+b
  •  print(“Sum of two numbers is:”, sum)
  • addition(5, 6)

Output:

Sum of two numbers is: 11

Python – required arguments

Output:

Python – required arguments – output

2.Keyworded Arguments:

When we use keyword arguments in a function call, the caller identifies the arguments by the argument name.

Example:

  • def language(lname):
  •  print(“Current language is:”, lname)
  • language(lname = “Python”)

Output:

Current language is: Python

Python – keyworded arguments

Output:

Python – keyworded arguments – output

3.Default Arguments:

When a function is called without any arguments, then it uses the default argument.

Course Curriculum

Enroll in Python Training Cover In-Depth Concepts By Top-Rated Instructors

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

Example:

  • def country(cName = “India”):
  •  print(“Current country is:”, cName)
  • country(“New York”)
  • country(“London”)
  • country()

Output:

  • Current country is: New York
  • Current country is: London
  • Current country is: India
  • Python – default arguments

Output:

Python – default arguments – output

4.Variable-length Arguments:

If you want to process more arguments in a function than what you specified while defining a function, then these type of arguments can be used.

Example 1:

Non – Keyworded argument

  • def add(*num): 
  •  sum = 0
  •  for n in num: 
  •  sum = n+sum
  • print(“Sum is:”, sum)
  • add(2, 5)
  • add(5, 3, 5)
  • add(8, 78, 90)

Output:

  • Sum is: 7
  • Sum is: 13
  • Sum is: 176
  • Python – variable length arguments Example 1
  • Python – variable length arguments Example 1 Output

Example 2:

Keyworded arguments

  • def employee(**data):
  • for(key, value in data.items()):
  • print(“The value {} is {}” .format(key,value))
  • employee(Name = “John”, Age = 20)
  • employee(Name = “John”, Age = 20, Phone=123456789)

Output:

  • Name is John
  • Age is 20
  • Name is John
  • Age is 20
  • Phone is 123456789
  • Python- variable length arguments Example 2

Output:

Python- variable length arguments Example 2 Output

Types of Python Functions

There are many types of Python functions. And each of them is very vital in its own way. The following are the different types of Python Functions:

  • Python Built-in Functions.
  • Python Recursion Functions.
  • Python Lambda Functions.
  • Python User-defined Functions.

Let us check out these functions in detail. Beginning with Built-in functions as they are very easy to understand and implement.

Python’s Built-In Functions

The Python interpreter has a number of functions that are always available for use. These functions are called built-in functions. For example, the print() function prints the given object to the standard output device (screen) or to the text stream file.

In Python 3.6, there are 68 built-in functions. But for the sake of simplicity, let’s consider the most popular functions and we can build up our knowledge from there.

Python abs() Function

Definition

The abs() function returns the absolute value of the given number. If the number is a complex number, abs() returns its magnitude.

syntax

  • The syntax of the abs() is:
  • abs(num)

Parameters

The abs() function takes a single argument:

    1. 1.integer
    2. 2.floating number
    3. 3.complex number

Example

  • # random integer
  • integer = -20
  • print(‘Absolute value of -20 is:’, abs(integer))
  • floating = -30.33
  • print(‘Absolute value of -30.33 is:’, abs(floating))

Output

Absolute value of -20 is: 20 Absolute value of -30.33 is: 30.33

Python all() Function

Definition

The all() function returns True when all elements in the given iterable are true. If not, it returns False.

Syntax

  • The syntax of the all() is:
  • all(iterable)

Parameters

The all() function takes a single parameter:

Example

  • # all values true
  • l = [1, 3, 4, 5]
  • print(all(l))
  • # all values false
  • l = [0, False]
  • print(all(l))
  • # one false value
  • l = [1, 3, 4, 0]
  • print(all(l))
  • # one true value
  • l = [0, False, 5]
  • print(all(l))
  • # empty iterable
  • l = []
  • print(all(l))

Output

True False False False True

Python ascii() Function

Definition

The ascii() function returns a string containing a printable representation of an object. It escapes the non-ASCII characters in the string using \x, \u or \U escapes.

Syntax

The syntax of ascii() is:

ascii(object)

Parameters

The ascii() function takes an object (like strings, lists, etc).

Example

  • normalText = ‘Python is interesting’
  • print(ascii(normalText))
  • otherText = ‘Pythön is interesting’
  • print(ascii(otherText))
  • print(‘Pyth\xf6n is interesting’)

Output

‘Python is interesting’ ‘Pyth\xf6n is interesting’ Pythön is interesting

Python bin() Function

Definition

The bin() function converts and returns the binary equivalent string of a given integer. If the parameter isn’t an integer, it has to implement the __index__() method to return an integer.

python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Syntax

The syntax of the bin() is:

bin(num)

Parameters

The bin() function takes a single parameter:

Example

  • number = 5
  • print(‘The binary equivalent of 5 is:’, bin(number))

Output

The binary equivalent of 5 is: 0b101

Python compile() Function:

Definition

The compile() function returns a Python code object from the source (normal string, a byte string, or an AST object).

Syntax

  • The syntax of compile() is:
  • compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Parameters

  • source- a normal string, a byte string, or an AST object.
  • filename- file from which the code was read. If it wasn’t read from a file, you can give a name yourself.
  • mode- Eitherexecorevalorsingle.
    • eval- accepts only a single expression.
    • exec- It can take a code block that has Python statements, classes, functions, and so on.
    • single- if it consists of a single interactive statement.
  • flags(optional) anddont_inherit(optional) – controls which future statements affect the compilation of the source. Default Value: 0.
  • optimize(optional) – optimization level of the compiler. Default value -1.

Example

  • codeInString = ‘a = 5\nb=6\nsum=a+b\nprint(“sum =”,sum)’
  • codeObejct = compile(codeInString, ‘sumstring’, ‘exec’)
  • exec(codeObejct)

Output

  • sum = 11

Python dict() Function

Definition

  • dict() creates a dictionary in Python.
  • Different forms of dict() are:
  • class dict(**kwarg)
  • class dict(mapping, **kwarg)
  • class dict(iterable, **kwarg)

Example

  • numbers = dict(x=5, y=0)
  • print(‘numbers = ‘,numbers)
  • print(type(numbers))
  • empty = dict()
  • print(’empty = ‘,empty)
  • print(type(empty))

Output

  • empty = dict() print(’empty = ‘,empty) print(type(empty))

Conclusion

  • Functions help a large program to divide into a smaller method that helps in code re-usability and size of the program.
  • Functions help in better understating of a code for the users as well.
  • Using python input/output functions, we can get the input from the user during run-time or from external sources like text file etc.
  • If we want to write a huge number of data into a file then we can achieve it using Python file output methods.

Are you looking training with Right Jobs?

Contact Us

Popular Courses