Programming in Python II: Working with Numbers Computer Science 105 Boston University

advertisement
Programming in Python II:
Working with Numbers
Computer Science 105
Boston University
Spring 2012
David G. Sullivan, Ph.D.
Data Types in Python
• In Python and other programming languages, different kinds
of data are stored and manipulated differently.
• A data type specifies:
• a domain: a set of possible values (as in SQL)
• a set of operations that can be performed on values
of that type
• In Python, there are several different data types for numbers:
• regular integers: int
• "long" integers: long
• numbers that can have fractional parts
(floating-point numbers): float
• like the REAL type in SQL
• used whenever a value has a decimal point
Data Types in Python (cont.)
• To determine the type of a value, we can use the built-in
type() function.
• examples:
>>> type(12)
<type 'int'>
>>> type(3.1495)
<type 'float'>
>>> type(3.0)
<type 'float'>
>>> type(2 ** 100)
<type 'long'>
>>> foo = 100
>>> type(foo)
<type 'int'>
>>> type(input)
<type 'builtin_function_or_method'>
Data Types and Variables
• Variables in Python do not have a type, so it's acceptable
to change the type of the value assigned to a variable.
• examples:
>>> value = 3.1495
>>> print value
3.1495
>>> value = 5280
>>> print value
5280
>>> value = 'Hello world!'
>>> print value
Hello world!
Representing Integers
• Like all values in a computer, integers are stored as
binary numbers – sequences of bits (0s and 1s).
• With n bits, we can represent 2n different values.
• examples:
• 2 bits give 22 = 4 different values
00, 01, 10, 11
• 3 bits give 23 = 8 different values
000, 001, 010, 011, 100, 101, 110, 111
• If we only cared about non-negative values, we could use
n bits to represent any integer from 0 to 2n – 1
• When we allow for negative integers (which Python does)
n bits can represent any integer from –2n-1 to 2n-1 – 1.
• there's one fewer positive value to make room for 0
Representing Integers (cont.)
• The number of bits used for an int depends on the CPU.
• it's often 32 bits (4 bytes)
• with 32 bits, an int can represent any value from
–231 to 231 – 1 (approx. +/–2 billion)
• For integer values that are outside the range of possible values
for the int type, Python uses the long type.
• it can be used to represent an arbitrarily large integer!
• Python will automatically use a long value when the result
of an operation requires it
Different Data Types Have Different Operations
• Recall the list of operators for numbers:
+
addition
subtraction
*
multiplication
/
division
**
exponentiation
%
modulus: gives the remainder of a division
example:
11 % 3 evaluates to 2
Different Data Types Have Different Operations
• Recall the list of operators for numbers:
+
addition
subtraction
*
multiplication
/
division
**
exponentiation
%
modulus: gives the remainder of a division
example:
11 % 3 evaluates to 2
• There are really three sets of operators: one set for int values,
one for float values, and one for long values.
• In most cases, the operators work the same way regardless
of the type of the number.
• However, there's one important exception!
The Division Operator
• The / operator behaves differently on integers than it does
on floating-point values.
• examples:
>>> 5.0 / 3.0
1.6666666666666667
>>> 5 / 3
1
>>> 11 / 5
2
• There are two types of division:
• integer division, which discards the fractional part of the
result (i.e., everything after the decimal)
• used when you divide two integer values
• floating-point division, which keeps the fractional part
• used when at least one of the values is a float
Using the Division Operator
• Recall our change-adder program:
quarters = input("number of quarters? ")
dimes = input("number of dimes? ")
nickels = input("number of nickels? ")
pennies = input("number of pennies? ")
cents = quarters*25 + dimes*10 + nickels*5 + pennies
print "you have", cents, "cents"
• Let's change it to print the result in dollars and cents.
• for example, 327 cents would print as 3 dollars, 27 cents
cents = quarters*25 + dimes*10 + nickels*5 + pennies
dollars =
cents =
print "you have", dollars, "dollars and",
print cents, "cents"
Using the Division Operator (cont.)
• Let's write code to convert a quiz grade to a percent.
• assume for now that the quiz is worth 30 points
• The following won't work.
>>> pointsEarned = 25
>>> print pointsEarned / 30 * 100
• What do we need to do to fix it?
>>>
A Grade Calculator Program
• Let's say that we want to write a program to convert an arbitrary
number of grades to percentages.
• We'll assume that all of the grades are for the same test/quiz.
• We'll allow the user to specify the number of possible points.
• Here's the algorithm in pseudocode:
user inputs the number of grades (numGrades)
user inputs the number of possible points (possible)
repeat numGrades times:
user inputs a grade (grade)
percent = grade / possible * 100
print percent
A Grade Calculator Program (cont.)
• Here's the algorithm in pseudocode:
user inputs the number of grades (numGrades)
user inputs the number of possible points (possible)
repeat numGrades times:
user inputs a grade (grade)
percent = grade / possible * 100
print percent
• Let’s convert it to Python:
• Problem: how do we force Python to use floating-point division?
Type Conversions
• Recall: Python performs floating-point division provided that
at least one of the values is a floating-point number.
• When both values are integers and we want floating-point
division, we need to explicitly convert one of the values using
the float() function:
percent = grade / float(possible) * 100
or
percent = float(grade) / possible * 100
• Would this work?
percent = float(grade / possible) * 100
Type Conversions (cont.)
• There are built-in functions for converting to any numeric type:
• float(n): converts n to a float
• int(n): converts n to an int, discarding any fractional part
• long(n): converts n to a long
• Examples:
>>>
8
>>>
8L
>>>
8L
>>>
int(8.72532)
long(8)
long(8.72532)
2**60
1152921504606846976L
>>> float(2**60)
1.152921504606847e+018
>>> int(2**60)
1152921504606846976L
Type Conversions (cont.)
• Using a type-conversion function does not change the type
of the value stored in memory.
• examples:
>>> measurement = 3.7
>>> int(measurement)
3
>>> measurement
3.7
• How could we change the type of the value stored in memory?
>>>
Rounding a Number
• round(n, d) rounds the number n to d places after the decimal:
>>> round(8.7467, 2)
8.75
>>> round(8.7467, 0)
9.0
>>> round(8.45, 0)
8.0
• If you omit the second argument, 0 is assumed:
>>> round(8.72532)
9.0
>>> round(8.45)
8.0
• To get the result of round() as an int, use the int() function:
>>> int(round(8.7467))
9
Floating-Point Values
• The decimal representation of floating-point values has limited
precision (e.g., 2/3 is only approximately equal to 0.666666667).
• In a computer, the binary representation of floating-point values
also has limited precision – and it shows up in different ways.
>>> 0.1
0.10000000000000001
>>> round(8.4321, 1)
8.4000000000000004
• Printing a floating-point value will usually give the level of
precision expected for a decimal representation.
>>> print 0.1
0.1
>>> print round(8.4321, 1)
8.4
• This limited precision influences how we compare FP values.
Python's Math Module
• Python comes with a math module that contains definitions for
a number of mathematical functions and constants, including:
• sqrt(n): computes the square root of a number
• trigonometric functions: sin(n), cos(n), tan(n)
• constants: pi, e
• To use them, we need to:
• import the module
• prepend the name of the module (e.g., math.sqrt(25))
>>> math.sqrt(25) # won't work before import
…NameError: name 'math' is not defined
>>> import math
>>> math.sqrt(25)
5.0
>>> math.pi
3.1415926535897931
Height Converter
• Let's design and write a program that reads a height in
centimeters and computes:
• the height in inches (rounded to the nearest inch)
• the height in feet, which any fraction of a foot expressed
in inches
• Example interaction:
Enter your height in cm: 172
You are 68 inches tall (5 feet, 8 inches).
• Conversion factor: 1 cm = 0.393700787 inches
Height Converter (cont.)
• Pseudocode:
• Python code:
Download