Arithmetic Operations, Type Conversions, and Input





If you can't write it down in English, you can't code it.
                     -- Peter Halpern



If you lie to the computer, it will get you.
                    -- Peter Farrar










Review: Operator Precedence and Arithmetic



Recall:

Operator precedence - highest to lowest

Note
: If a binary operation has one float operand and one int operand, the int will be converted to a float, and the result will be a float.




Examples:
result = 2 * ((16 - 4) / 2)  # result is set to 12
result = 13 % 2 - 1           # result is set to 0
result = 13 % 2 * 4          # result is set to 4
result = 5**2                    # result is set to 25





Type Conversions


Integers that are too large to be stored in 32 bits are converted to the type long (or long int).

A literal value may be specified as a long by adding an "L" suffix to the number:

>>> 2L
2L

>>>5**31
4656612873077392578125L



Explicit Conversions from one type to another

Python has functions that will convert a number from one type to another:


>>> float(3)
3.0
>>> int(3.9)
3
>>> int(101.566)
101
>>> long(3.9)
3L


Example:
test1 = 90
test2 = 84
test3 = 95

sum = test1 + test2 + test3
print sum/3
print float(sum)/3

Output:
89
89.66666666667


When a float is converted to an int, the fractional part of the value is discarded.
If we want to round to the nearest whole number, we can use the round() function:

>>> round(3.4)
3.0
>>> round(3.5)
4.0
>>> round(3.778)
4.0
>>> int(round(3.56))
4






Input from the Keyboard





The input() function

The input function:

Example:
>>> num1 = input("Please enter the first exam score: ")
Please enter the first exam score: 77
>>> num2 = input("Please enter the second exam score: ")
Please enter the second exam score: 89
>>> sum = num1+num2
>>> print "Average=", float(sum)/2
Average = 83.0



Example: Write a program that asks the user to enter 3 (integer) exam scores, and then prints the average.



The raw_input() function

The raw_input function:

Example:
>>> color = raw_input("Please enter your favorite color: ")
Please enter your favorite color: blue
>>> print "hey, I like", color, "too!"
hey, I like blue too!



Example: Write a program that asks the user to enter a line of text, and then prints the line to the screen.