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
- Parentheses
- **
- * / % <--- performed in
order from left to
right
- + -
<--- performed in
order from left to right
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() -
Converts a number to type float
- int() -
Converts a number to type int
- long() -
Converts a number to type long
>>>
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
- Read data from the user during program
execution
- input()
function - reads numeric values from the keyboard
- raw_input()
function - reads strings from the keyboard
The input()
function
The input
function:
- prompts the user to enter a number
- takes the number entered at the keyboard and assigns it
to a variable
- Format: myVariable = input('My message asking the user
to enter some number')
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:
- prompts the user to enter a string
- the string that is entered at the keyboard is assigned
to a variable
- Format: myStringVariable =
raw_input('My prompt to the user')
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.