Python Calculator: From Beginner to Pro 2023

Python Calculator: From Beginner to Pro

Here's one way to make a simple calculator using Python:



Start by defining a function called Python program calculator(). This function will contain the code for our calculator Python Calculator: From Beginner to Pro

Inside the calculator() function, use input() to ask the user for the operation they would like to perform (e.g. "addition", "subtraction", "multiplication", "division"). Store the input in a variable called operation.

Use input() again to ask the user for the two numbers they would like to perform the operation on. Store the input in variables called num1 and num2.

Use an if-elif statement to check the value of operation. Depending on the value of operation, perform the corresponding arithmetic operation on num1 and num2.

Print the result of the arithmetic operation to the console using print().

Call the calculator() function to run the code.


Here's what the complete code might look like:


def calculator():

    operation = input("What operation would you like to perform? (addition, subtraction, multiplication, division) ")

    num1 = int(input("Enter the first number: "))

    num2 = int(input("Enter the second number: "))


    if operation == "addition":

        result = num1 + num2

    elif operation == "subtraction":

        result = num1 - num2

    elif operation == "multiplication":

        result = num1 * num2

    elif operation == "division":

        result = num1 / num2

    else:

        result = "Invalid Operation"


    print(result)


calculator()


This is just a simple example, and you can add more to it, error handling, or more complex operations.

Post a Comment (0)
Previous Post Next Post