Python 3.8 Tutorial

Functions in Python

The very basics of Functions in Python and how they work.

Saranjeet Singh

--

Functions are used everywhere in the programming. It is really important for us to know what exactly the functions are and what they do? To understand that, first, we will see how we can write programs in Python without using functions.

sum_of_two_numbes.pyx=4y=3sum = x + yprint(sum)//7

program is pretty simple, we are adding two variables x and y. However, what we will be doing if we have 10 different values of x and y to add?

python program to add two numbes
def add_two_numbers(n):   for i in range(1,n+1):        x = int(input('enter value for x: '))        y = int(input('enter value for x: '))        sum_of_two = x + y        print ('sum of two numbers are: ',sum_of_two)        return 'program ends :)'
n = int(input('how many times: '))print(add_two_numbers(n))
The output of the program

Always remember, whenever you want some kind of repetition in the code, you have to use some kind of Loops. Python has While and For loops. For this purpose, we will be using For loop.

x and y will take two integer input from the user ( not considering the tests!) and are placed under for loop. The loop is like a counter and will repeat the same process until it reaches its end ( n+1 times). The sum variable will add both x and y and the print statement will print the result on the screen. What would happen if we won’t put any return statement?

Outside the function, we have declared n and will pass this as an argument to our function. What is the argument you would ask? Let’s make a list of items necessary to create and understand a function.

  1. def keyword
  2. return statement
  3. arguments

Usually, only these three terms should be enough to understand functions in python. Now functions should look less intimidating :)

  1. def keyword: it's simple. Whenever you want to declare a function, use def keyword. Done!
  2. return just returns the final calculations of the function. If you don’t put a return statement, python by default will return None.
  3. arguments: The purpose of an argument is to ready the function for inputs. In our example above, n is the argument. So in order to function start working, it needs to have at least 1 argument otherwise it will give an error saying function needs at least one argument.

That’s all you need to know for a function. Even the advanced function will use these 3 things in order to calculate the result of the program. So, always remember these three terms and you will be just fine.

In the future lesson, we will work on advanced functions and classes.

--

--

Saranjeet Singh

I write tutorials on Python, JavaScript, React, and Django. I write for InPlainEnglish and TheStartUp .