Jeeqs

Operators/Order of Operation

1.4 > A Gentle Introduction to Programming Using Python > EECS > MIT

Python has the ability to be used as a cheap, 5-dollar calculator. In particular, it supports basic mathematical operators +, -, , / as well as the power operator (*) and the modulus operator (%). ￼ Program Text:

x=5+7 print x
y = x + 10 print y


Output:

12
22


Note that we can use variables in the definition of other variables! Mathematical operators only work on numbers­ ints or floats. Statements such as $\verb*’Hi’ + 5*$ or $\verb*’5’ + 7*$ will not work.

Part I: Input the following sets of equations, and note the difference between int arithmetic and float arithmetic. You can do this just in your interpreter (you don’t need to turn anything in for this part), but pay attention to the output!

1. $\frac{5}{2}$, $\frac{5}{2.0}$ and $\frac{5.0}{2}$ Note that as long as one argument is a float, all of your math will be floating point!

2. $7 * \left(\frac 12\right)$ and $7 * \left(\frac{1}{2.0}\right)$

3. 5∗∗2, 5.0∗∗2, and 5∗∗2.0

4. $\frac{1}{3.0}$ Note the final digit is rounded. Python does this for non-terminating decimal numbers, as computers cannot store infinite numbers! Take $6.004$ to find out more about this...

Part II: In the solution, transcribe the following equations into Python (without simplifying!), preserving order of operation with parenthesis as needed. Save each as the value of a variable, and then print the variable.

1. $\frac{3 \times 5}{2 + 3}$

2. $\sqrt{7 + 9} \times 2$

3. $(4 - 7)^{3}$

4. $\sqrt[4]{-19+100}$

5. $\verb*6 mod 4*$ - If you aren’t familiar with modular arithmetic, it is pretty straightforward- the modulus operator, in the expression $\verb*x mod y*$, gives the remainder when x is divided by y. Try a couple modular expressions until you get the hang of it.

￼￼￼Part III: In the solution, use order of operation mathematics to create two equations that look the same (ie, have the same numbers) but evaluate to different values (due to parenthesization). Save each as the value of a variable, then print the variables.

Please note that all math functions are available directly in the console. For example, sqrt(2) evaluates to the root of 2

Course
MIT, EECS : A Gentle Introduction to Programming Using Python