Built with Tutify.io

    AIStudyLabs

    Simple Calculator Using Functions

    Simple Calculator Using Functions

    Introduction

    In this final lesson, we will create a simple calculator leveraging Python's capabilities with functions. You will explore defining functions, returning values, and structuring your program to handle various arithmetic operations. This lesson integrates everything you've learned, focusing on building a functional and modular calculator program that efficiently manages user inputs and displays outputs.

    Understanding Function Definitions

    Functions in Python allow you to encapsulate code into reusable blocks, improving readability and efficiency. In our calculator, each arithmetic operation will be a separate function, enhancing modularity.

    Here's a simple function definition:

    # Function to add two numbers
    def add(x, y):
        return x + y
    

    This add function takes two parameters, x and y, performs addition, and returns the result.

    Implementing Basic Arithmetic Operations

    We'll define functions for subtraction, multiplication, and division. Each function will handle two numbers and produce the respective arithmetic result.

    # Function to subtract two numbers
    def subtract(x, y):
        return x - y
    
    # Function to multiply two numbers
    def multiply(x, y):
        return x * y
    
    # Function to divide two numbers
    def divide(x, y):
        # Avoid division by zero
        if y == 0:
            return "Error: Division by zero is undefined."
        return x / y
    

    Handling User Input and Output Processes

    Now that we have defined our basic operations, we will manage user input and interaction. We'll prompt users to enter two numbers and an operator, then call the appropriate function.

    # Main function to run the calculator program
    def calculator():
        # Dictionary to map operator symbols to function calls
        operations = {
            '+': add,
            '-': subtract,
            '*': multiply,
            '/': divide
        }
    
        # Input from the user
        num1 = float(input("Enter first number: "))
        operator = input("Enter operator (+, -, *, /): ")
        num2 = float(input("Enter second number: "))
    
        # Check for valid operator and execute respective function
        if operator in operations:
            result = operations[operator](num1, num2)
            print(f"Result: {num1} {operator} {num2} = {result}")
        else:
            print("Invalid operator. Please try again.")
    

    Utilizing Return Values for Function Results

    Each operation function returns a value that the calculator function captures and displays. This separation of concerns ensures each part of the program handles its specific responsibility, thus maintaining clean and effective code.

    Creating a Modular Calculator Program Structure

    Our program's modular nature comes from using functions to encapsulate distinct actions. Each function does one job, enabling easy updates and maintenance.

    Here's how everything ties together in the complete program:

    # Main Calculator Program
    if __name__ == "__main__":
        while True:
            calculator()
            # Check if the user wants to perform another calculation
            another_calculation = input("Do you want to perform another calculation? (yes/no): ").strip().lower()
            if another_calculation != 'yes':
                break
        print("Thank you for using the calculator!")
    

    This code provides a continuous user interaction loop, allowing for multiple calculations until the user decides to stop.

    Summary / Key Takeaways

    In this lesson "Lesson 50: Simple Calculator Using Functions", you have learned:

    Master Python by Writing 50 Programs — Chapter 7: File Handling and Real Programs

    Python Basics Programs

    Number-Based Programs

    Loops and Mathematical Programs

    String-Based Programs

    List-Based Programs

    Dictionary and Set Programs

    Chapter 7: File Handling and Real Programs

    Tutorial Not Found