Python - 19

Python - 19: Building a Calculator

Combine input, numbers, math, and functions to build a simple calculator.

Your challenge: Ask for two numbers, pass them to a function, and display the result.

✦ Python Editor
▶ Output

Convert input to numbers

input() returns text, so use float() when you want the user to enter numbers that may include decimals.

For example: number1 = float(input("Enter first number: "))

Use a calculator function

The add_numbers() function accepts two values and returns their sum.

You can store that returned value: answer = add_numbers(number1, number2)

Other math operators

Python uses + for addition, - for subtraction, * for multiplication, and / for division.

Try it: Change the function so it multiplies the two numbers instead of adding them.

Good Python habit: Put a calculation inside a function when you want the same calculation to be easy to reuse.

👀 Show Example Solution
print("Simple Calculator")

def add_numbers(a, b):
    return a + b

number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))

answer = add_numbers(number1, number2)

print("Answer:")
print(answer)

The program converts the user's input into numbers, sends those numbers to the function, and prints the returned result.