User-defined Functions with Python

User-defined Functions with Python

User-defined Functions with Python

Functions

Functions are used in programming languages to organize code better and to provide code reusability. If we have to perform several tasks in our code, we can define functions for each of them separately. Then, we can reuse those functions in our main code when we need to perform the task repetitively. This way, we can abstract away the implementation details from our main code.

Python provides a variety of built-in functions to make our lives easier. Further, Python provides us the capability of defining our own functions. In this article we will be learning how to define our own functions.

User-defined Functions

In our previous article we implemented a simple calculator program. Today let’s learn about functions and use them in our calculator program.

def add(num1, num2):
    answer = round(num1 + num2, 2)
    return answer

Above code snippet shows how we can define a function to add two numbers. We use the def keyword to define a function. We use add as the function name (You may use any name you prefer). This function has two parameters to catch the values we pass from our main code. Inside our function, we add the two numbers and assign the result to a variable named answer. Finally, we can return the answer with the return keyword.

Alternatively, we can perform the operation and return the value in the same line, since we have no use of assigning it to a variable.

def add(num1, num2):
    return round(num1 + num2, 2)

Calculator with Functions

Now we can define four functions to perform each operation. In our main function, we can invoke these functions and pass user input values as arguments. Don’t forget to invoke the function main at the end of the code!

def main():
    number1 = float(input("Enter 1st number: "))
    number2 = float(input("Enter 2nd number: "))

    print(f"{number1} + {number2} = {add(number1, number2)}")
    print(f"{number1} - {number2} = {subtract(number1, number2)}")
    print(f"{number1} * {number2} = {multiply(number1, number2)}")
    print(f"{number1} / {number2} = {divide(number1, number2)}")


def add(num1, num2):
    return round(num1 + num2, 2)

def subtract(num1, num2):
    return round(num1 - num2, 2)

def multiply(num1, num2):
    return round(num1 * num2, 2)

def divide(num1, num2):
    return round(num1 / num2, 2)

main()

Comments

Popular posts from this blog

Data Structures - Part 1

OOP with Python - Part 2

OOP with Python - Part 1