This is the solution to the simple calculator exercise in the fifth tutorial in the introduction to programming with Python series.
The tutorial can be found here:
https://www.youtube.com/watch?v=-I1QcEA8a7A
For this exercise you have to write a python program that will prompt the user for an operation (add, subtract, multiply, divide) then prompt the user for two numbers and perform the operation on them and display the result to the user.
Here is a sample output when you run your calculator python program (call it calc.py):
The program itself should be simple enough. You can copy this code into a python file (calc.py) and execute it.
Please note that in python lines that start with the pound sign are comment lines.
Comment lines give information about the code but do not affect how it executes. Python will ignore them.
The tutorial can be found here:
https://www.youtube.com/watch?v=-I1QcEA8a7A
For this exercise you have to write a python program that will prompt the user for an operation (add, subtract, multiply, divide) then prompt the user for two numbers and perform the operation on them and display the result to the user.
Here is a sample output when you run your calculator python program (call it calc.py):
The program itself should be simple enough. You can copy this code into a python file (calc.py) and execute it.
Please note that in python lines that start with the pound sign are comment lines.
Comment lines give information about the code but do not affect how it executes. Python will ignore them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# First, prompt the user for the operation he/she wishes to execute | |
op = input('What operation do you wish to execute?(add, subtract, multiply, divide): ') | |
# Now prompt the user for the two numbers to execute the operation on | |
num1 = int(input('Enter first number: ')) | |
num2 = int(input('Enter second number: ')) | |
# Use if/elif to execute the desired operation | |
if op == 'add': | |
print('Your result is: ', num1 + num2) | |
elif op == 'subtract': | |
print('Your result is: ', num1 - num2) | |
elif op == 'multiply': | |
print('Your result is: ', num1 * num2) | |
elif op == 'divide': | |
print('Your result is: ', num1 / num2) | |
else: | |
# It seems the user entered an operation other than the supported ones. Give error message. | |
print('Sorry, I do not recognize this operation') | |
No comments:
Post a Comment