Lesson 21 of 30
Lesson 21 ? Mini calculator
Title: Build a calculator with functions
Description: Make small functions for adding, subtracting, multiplying, and dividing.
Why it matters for kids: A calculator project shows how functions can work together.
1. Add numbers
def add(first_number, second_number):
return first_number + second_number
print(add(3, 4))
print(add(10, 5))2. More operations
def subtract(first_number, second_number):
return first_number - second_number
def multiply(first_number, second_number):
return first_number * second_number
print(subtract(10, 3))
print(multiply(4, 5))3. Ask the user
first_number = int(input("First number: "))
second_number = int(input("Second number: "))
print("Sum:", first_number + second_number)4. Choose an operation
operation = input("Choose + or -: ")
first_number = int(input("First number: "))
second_number = int(input("Second number: "))
if operation == "+":
print(first_number + second_number)
elif operation == "-":
print(first_number - second_number)
else:
print("Unknown operation.")5. Easy examples
def divide(first_number, second_number):
return first_number / second_number
print(divide(12, 3))def square(number):
return number * number
print(square(6))def add_bonus(score):
return score + 10
print(add_bonus(50))6. Mini challenge
Click each example to open it.
Example 1
Create an add function.
Example 2
Create a subtract function.
Example 3
Create a multiply function.
Example 4
Create a divide function.
Example 5
Ask for the first number.
Example 6
Ask for the second number.
Example 7
Print the sum.
Example 8
Let the user choose plus.
Example 9
Let the user choose minus.
Example 10
Add multiply to the menu.