RU beehive logo ITEC dept promo banner
ITEC 109
2014spring
ibarland

homeinfolectslabsexamshws
D2Lbreeze (snow day)tutor/PIs

lab06-casting
quotient vs division
casting ints/floats

Recall that + means two different things, depending on context (whether the +-sign is surrounded by strings or by numbers1

It turns out, / means two different things, depending on context:

It can be a gotcha, to have the two types of division sharing the same name (unlike +, which is rarely confusing, since the two types of “addition” are different enough from each other). Consider:

We already mentioned that python follows the convention PEMDAS (or, “my dear aunt sally”). More formally:
When evaluating an expression, python has the following “order of operations”:
  1. Do things inside parentheses first (including arguments to function calls)
  2. Going left-to-right, do any multiplication/divisions2.
  3. Finally, go left-to-right and do any addition/subtraction (including string-concatenation)
hint:If it helps human-readability, add parentheses (as well as spaces) to your code, even if they aren't strictly necessary for python's order-of-operations.
Ideally, a programmer can read your code-expression and not even have to think/wonder for an instant, whether the order-of-operations is doing anything unexpected.

Converting between int and float

Sometimes you want to convert an int to a float, and you can't just add a trailing “.0”. Consider the ratio of letters in the word "Virginia Polytechnic Institute" (30) to the letters in "R.U." (4): we want 30.0/4.0, not 30/4: len("Virginia Polytechnic Institute") / len("R.U.") The solution is: call a function whose task is to convert integers to floats. This function is named “float”: e.g. float(3) = 3.0.

By the way, there is also a function that converts floats to ints. Can you guess its name? What result does it answer, if you give it 3.9? -2.8?



1 I guess technically, + gives a slightly-different answer for 2.0 + 3.0 vs. 2+3, too.      

2 The remainder operator (“%”) is a form of division.      

homeinfolectslabsexamshws
D2Lbreeze (snow day)tutor/PIs


©2014, Ian Barland, Radford University
Last modified 2014.Feb.03 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme