Learn Python from scratch: Part 4. Use Python as a calculator

Let’s go back to primary school days and refresh our math skills. After recalling your math skills, you can apply your math skills in Python scripting. I have tabulated the most common computing symbols, their meanings and gave each examples. Simple Python examples are also provided as part of below table and we’ll use this to create our next script, script3.py.

Symbol Meaning Example Python example
+ Plus 1 + 1 = 2 print “Simple plus: 1+1 equals”, 1+1
Minus 2 – 1 = 1 print “Simple minus: 2 – 1 equals”, 2 – 1
* Asterisk 2 * 2 = 4 print “Simple multiple: 2 times 2 equals”, 2 * 2
/ Slash 2/2 = 1 print “Simple division: 2 divide by 2 equals”, 2 / 2
% Percent = Modulo 5 % 2 = (5 – (2 x 2)) = 1 print “simple modulo, 5%2 equals”, 5 % 2
< Less-than 1 < 2 print “True or False: 1 is less than 2?”, 1 < 2
> Greater-than 2 > 1 print “True or False: 2 is greater than 1?”, 2 > 1
<= Less-than-equal 1 <= 2 print “True or False: 1 is less than equal to 2?”, 1 <= 2
>= Greater-than-equal 2 >= 1 print “True or False: 2 is greater than equal to 1?”, 2 >= 1
**         Exponents 5 to the power of 4 5x5x5x5 = 5**4 = 625

Task: Copy and paste the following information and save it as script3.py, then run it in your terminal environment.

print “Simple plus: 1+1 equals”, 1+1
print “Simple minus: 2 – 1 equals”, 2 – 1
print “Simple multiple: 2 times 2 equals”, 2 * 2
print “Simple division: 2 divide by 2 equals”, 2 / 2
print “simple modulo, 5%2 equals”, 5 % 2
print “True or False: 1 is less than 2?”, 1 < 2 print “True or False: 2 is greater than 1?”, 2 > 1
print “True or False: 1 is less than equal to 2?”, 1 <= 2 print “True or False: 2 is greater than equal to 1?”, 2 >= 1


Linux Session: compare the output in Python after running the script.

script3 - linux


Windows Session: compare the output in Python after running the script.

script3 - windows


To help your understanding of % (modulo) usage, I have included two examples of % calculation. Please note, these examples are sourced from Python training site on internet and I have added my own explanation for a full understanding of its use in simple calculation. If you are already familiar with the use of modulo in Python calculation, please jump to Part 5:

Example 1:

3 + 2 + 1 – 5 + 4 % 2 – 1 / 4 + 6

(3+2+1-5) + (4%2) – (1/4) + 6

1 + (0) – 1/4 + 6

(1) + (0) – (0) + 6

7

*Note: The 1/4=0 because we’re doing integer math here.

*Note:  (4%2) results in perfect division without any remainder, so 4/2 = 2 with the remainder of 0. So the resulting value is 0.


Example 2:

100 – 25 * 3 % 4

100 – (75 % 4)

100 – (75 – (4 x 18))  <<< you divide 75 into 4, until you get the remainder of 3

100 – 3

97


This sure is a slow learning process, but even to walk a 100 miles, you have to take a step at a time.

Leave a comment