In this lesson, you will create a simple calculator in Scratch. By the end of this project, you'll have a functioning calculator that can perform basic math operations (addition, subtraction, multiplication, and division).
Check out the final Scratch project below!
Key Concepts: Variables, User Input, Conditional Statements, Mathematical Operations
1. Ask Function & Conditional Logic
The Ask and Wait Block
The ask [ ] and wait block in Scratch is crucial for getting user input. It's like asking a question and waiting for an answer.
The "ask and wait" block, and the "answer" block that holds the reply
1. Drag the ask [ ] and wait block from the "Sensing" category.
2. Type your question in the block, e.g., "What operation do you want to perform?"
3. The user's answer is stored in the answer block.
Conditional Logic with If-Then Blocks
We use conditional logic to decide what operation to perform based on the user's input.
1. Drag an if [ ] then block from the "Control" category.
2. Use the = block from "Operators" to check the answer.
3. Add blocks inside the if-then to perform the chosen operation.
Pro Tip: Use multiple if-then blocks to handle different operations in your calculator.
2. Coding the Subtraction Operation
Getting the Numbers
Before we can subtract, we need to get two numbers from the user.
1. Use two ask [ ] and wait blocks to get both numbers.
2. Store each answer in a variable (e.g., 'number1' and 'number2').
Performing the Subtraction
Now let's subtract the numbers and show the result.
1. Use the - block from the "Operators" category.
2. Place your 'number1' and 'number2' variables in the subtraction block.
3. Use a say [ ] block to display the result.
Challenge: Can you modify this code to handle addition, multiplication, and division as well?
Homework and Exercises
Exercise 1: Complete Calculator
Extend your calculator to handle all four basic operations: addition, subtraction, multiplication, and division.
1. Add if-then blocks for each operation.
2. Use appropriate operator blocks for each calculation.
3. Test your calculator with different inputs.
Exercise 2: Advanced Operations
Add more advanced operations to your calculator.
1. Implement a square root function.
2. Add a power function (x to the power of y).
3. Include a modulo operation (remainder after division).
Remember: The key to becoming a great programmer is practice and creativity. Keep experimenting and building new things!