Calculator
Recall from lecture that we created a program to add two numbers together, calculator.py
. This program worked well, at least until a user entered something like “dog” or “cat!” Let’s explore how we can better guard against this type of malicious behavior, using a computing concept called an “exception.”
In a file called calculator.py
, implement a program in Python that prompts the user for two integers and then sums them together. If the user doesn’t cooperate, instead inputting a word (or a decimal!) for either prompt, kindly re-prompt them. Or, simply exit the program.
Before You Begin
Log into cs50.dev, click on your terminal window, and execute cd
by itself. You should find that your terminal window’s prompt resembles the below:
$
Next execute
mkdir calculator
to make a folder called calculator
in your codespace.
Then execute
cd calculator
to change directories into that folder. You should now see your terminal prompt as calculator/ $
. You can now execute
code calculator.py
to make a file called calculator.py
where you’ll write your program.
How to Test
Here’s how to test your code manually:
- Run your program with
python calculator.py
. Type1
followed by1
and press Enter. Your program should output:2
- Run your program with
python calculator.py
. Type1
followed bydog
and press Enter. Your program should either re-prompt the user for the second number, or exit after printing an error message.