Python - Understanding Functions (for beginners)

(a simple and quick read)

·

2 min read

Python functions are blocks of code that carry out particular tasks. Functions can accept inputs, often known as arguments, and are defined with the def keyword. Code can be reused and encapsulated using them.

To put it in plain language, we say, A function is a section of code that only executes when called. A function can take parameters, or data, as input. Data can be returned by a function.

## Performing Simple Arithmetic Operations with out using Function (a linear code)

Num1 = 60
Num2 = 5

Result1 = Num1 + Num2
print("The sum of numbers is:",Result1)

Result2 = Num1 - Num2
print("The difference of numbers is:",Result2)

Result3 = Num1 * Num2
print("The product of numbers is:",Result3)


### Performing Simple Arithmetic Operations using Function

Num3=80
Num4=8

def addition():
    add = Num3 + Num4
    print("The sum of num3 and num4 is:",add)

def sub():
    diff = Num3 - Num4
    print("The difference of num3 and num4 is:",diff)

def mul():
    product = Num3 * Num4
    print("The product of num3 and num4 is:",product)


addition() ### we need to explicitly invoke/call on the functions in python to get the code inside  the function executed
sub()
mul()

###OUTPUT for the above:
@skmak1111 ➜ /workspaces/python (main) $ python Test_Func.py
The sum of numbers is: 65
The difference of numbers is: 55
The product of numbers is: 300
The sum of num3 and num4 is: 88
The difference of num3 and num4 is: 72
The product of num3 and num4 is: 640
@skmak1111 ➜ /workspaces/python (main) $