Functions
Introduction​
Functions are known as building blocks of programs. A large problem can be divided into smaller functions, achieving modularity, reusability, and readability.
- A function accepts some inputs, performs computations, and outputs the results.
- Functions can be called as many times as we want after they are defined.
- Each function takes only one responsibility and is interdependent
- Functions are logical, modular, and readable to human eyes. With functions as modules, it is easier to maintain the programs further.
Built-in functions​
Built-in functions are pre-defined and part of the Python language such as print(), range(), and type().
User-defined functions​
User-defined functions are defined by users. To define a Python function, begin with keyword def followed by a function name. A function can have zero or some arguments and can return values. Arguments and return values interact with the calling function.
A Python function with no argument and no return value:
# Defining a function
def honk():
print("Car honks")
# Calling the function
honk()
Output:
Car honks
A Python function with arguments and return value:
# math_operation has three arguments and returns a value
def math_operation(num1, op, num2):
return eval(num1 + " " + op + " " + num2)
a, b = input("Enter two numbers (x, y): ").split()
op = input("Enter operator: ")
print(math_operation(a, op, b))
Output:
Enter two numbers: 25 6
Enter operator: *
150
Enter two numbers: 99 -10
Enter operator: -
109