Now that we know how to define and input numbers, let's move on to basic number operations and calculations.
Open lab2.py from Project 2 - Temp Converter
The basic mathematical operations are follows, and all can be found on the numpad of your keyboard:
Addition: +
Subtraction: -
Multiplication: *
Division: /
A little more advanced, you may be required to calculate remainders with the modulus operator %.
Or exponents with the exponent operator **.
Here we have used the float() function to convert our string into a a float, and the int() function to convert our second string into an int.
Complete the following requirements:
Ask the user for two numbers and store them in variables 'a' and 'b', converting to floats
Add 'a' and 'b' and store the result in a variable 'add_result'
Subtract 'b' from 'a' and store the result in a variable 'sub_result'
Multiply 'a' and 'b' and store the result in 'mul_result'
Divide 'a' by 'b' and store the result in 'div_result'
Raise 'a' to the power of 'b' and store in 'exp_result'
Calculate the modulus of 'a' and 'b' and store in 'mod_result'
Print the results of each calculation, with a description of the operation, e.g. "5 plus 3 is 8"
Press Ctrl + F5 to run the program or open a terminal and type python lab2.py
It should run without errors and you should see something like on the right:
Please enter the first number: 7
Please enter the second number: 3
The sum of 7.0 and 3.0 is 10.0
The difference between 7.0 and 3.0 is 4.0
The product of 7.0 and 3.0 is 21.0
The quotient of 7.0 divided by 3.0 is 2.333333
7.0 raised to the power of 3.0 is 343.0
The modulus of 7.0 and 3.0 is 1.0
You should now know how to perform a variety of number operations in Python.
Let's wrap up this lab by pushing our code to GitHub:
Enter a commit message. E.g. "Lab 2 complete"
Press Commit to main
Press Push origin