Data Types Data can have many different types
Python is dynamically typed In a dynamically typed language, a variable is
simply a value bound to a name; the value has a type -- like "integer" or "string" or "list"
-- but the variable itself doesn't. x=“hello”x=2.5
In a statically typed language, the variable itself has a type
if you have a variable that's an integer, you won't be able to assign any other type of value to it later.
2
The type function Tells you what type (or “class”) your data item
is. e.g.:>>> type(3)<type ’int’>>>> type(3.14)<type ’float’>>>>type(3+2.1j)<class 'complex'>
3
The type function Tells you what type (or “class”) your data item
is. e.g.:>>> myInt = -32>>> type(myInt)<type ’int’>>>> myFloat = 32.0>>> type(myFloat)<type ’float’>
4
Numeric Data TypesFor numbers we have two BASIC types: integers:
whole numbers with no fractional part
floating point number: numbers with fractional part WARNING: store only an approximation to real
numbers there is a limit to the precision, or accuracy, or the
stored values e.g. 10/3
5
Checkpoint: Why are there two basic types for numbers?
6
Checkpoint: Why are there two basic types for numbers? style:
an integer can’t be a floating point
efficiency: integer arithmetic is simpler, and therefore faster, than for
floating point numbers. If you don’t need a float, use an int
7
Numeric Data TypesWe also have: Complex numbers
combination of real and imaginary components Both represented by floating-point numbers imaginary part denoted by ‘j’ e.g. 3+2.1j
8
Python built-in numeric operators+ addition- subtraction* multiplication/ float division** exponentiation% remainderabs() absolute value// integer division
9
Numeric operationsFor the most part, operations on floats produce
floats and operations on integers produce integers e.g. ….
However, division is a bit more interesting. the / operator ALWAYS returns a floatbecause dividing two ints can produce a float
10
Numeric operationsFor the most part, operations on floats produce
floats and operations on integers produce integers e.g. ….
However, division is a bit more interesting. the / operator ALWAYS returns a floatbecause dividing two ints can produce a float
WHY IS THIS A GOOD IDEA?
11
Why is this a good idea? Many computer languages, including Fortran,
C, C++, and Java (and Python pre version 3), interpret a division operation a/b as integer division, if both operands a and b are integers. ONLY IF either a or b is a real (floating-point)
number, DOES a/b implies the standard mathematical float division.
This confusion leads to one of the most common errors in mathematical software not at all obvious for a newcomer to programming.
Python 3 fixes this!
12
Example: Temperature converter# convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Suzie Programmer
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/ 5 * celsius + 32
print "The temperature is", fahrenheit, "degrees Fahrenheit.”
main()
13
Numeric operations to ensure an integer result, use //
truncating division operator also known as floor division
examples….
14
CheckpointIn Python 3, the expression 10//3 will evaluate
as:a. 3.3333333333333333b. 3.3333333333333335c. 3d. 3.0
15
CheckpointIn Python 3, the expression 10/3 will evaluate
as:a. 3.3333333333333333b. 3.3333333333333335c. 3d. 3.0
16
CheckpointIn Python 3, the expression '10.0'*2 will
evaluate as:a. 20b. 20.0c. '10.010.0'd. Syntax error
17
CheckpointIn Python 3, the expression -7//3 will evaluate
as:a. -2b. -3c. -2.3333333333333335d. -2.3333333333333333
18
NOTE: Integer division of negative numbers Python (and Ruby) define integer division of or
by a negative number differently to C and Java.
e.g. -7//3 Java = -2 Python= -3
integer arithmetic is not as simple as it appears!
19
CheckpointIn Python 3, the expression 8//3*2.0 will
evaluate as:1. 5.3333333333333332. 103. 44. 4.0
20
Python Programming, 2/e21
Type Conversions We know that combining an int with an int
produces an int, and combining a float with a float produces a
float. What happens when you mix an int and float
in an expression?x = 5.0 + 2
What do you think should happen?
Python Programming, 2/e22
Type Conversions For Python to evaluate this expression, it must
either convert 5.0 to 5 and do an integer addition, or convert 2 to 2.0 and do a floating point addition.
Converting a float to an int will lose information
Ints can be converted to floats by adding “.0”
Python Programming, 2/e23
Explicit Type Conversion In mixed-typed expressions Python will
convert ints to floats.
Sometimes we want to control the type conversion. This is called explicit typing.
Python Programming, 2/e24
Type Conversions>>> float(22//5)4.0>>> int(4.5)4>>> int(3.9)3
>>> round(3.9)
4
>>> round(3)
3
Checkpoint: Explain in English what this program does
number = eval(input("Type in a number:\n") ) divisor = eval(input("What do you want to
divide by?")) intResult = number//divisor remainder = number%divisor print(number,"/", divisor, "=", intResult,
"remainder", remainder)
25
Math library Python provides many other useful
mathematical functions in a special math library.
A library is just a module that contains some useful definitions
26
Math libraryThe math functions operate on integers and
floats but do not work with complex numbers (a separate module – cmath - can be used to perform similar operations on complex numbers).
The return value of all functions is a float. All trigonometric functions assume the use of
radians.
27
Math librarysin(x) Returns the sine of x. cos(x) Returns the cosine of x. tan(x) Returns the tangent of x. acos(x) Returns the arc cosine of x. asin(x) Returns the arc sine of x. atan(x) Returns the arc tangent of x.
degrees(x) Converts x from radians to degrees.
radians(x) Converts x from degrees to radians.
28
Math library
exp(x) Returns e ** x. ceil(x) Returns the ceiling of x. floor(x) Returns the floor of x.
copysign(x,y) Returns x with the same sign as y. fabs(x) Returns the absolute value of x.
factorial(x) Returns xfactorial.hypot(x, y) Returns the Euclidean
distance,sqrt(x* x+ y* y). isinf(x) Return True if x is infinity.
29
Math libraryisnan(x) Returns True if x is NaN. ldexp(x, i) Returns x* (2 ** i). log(x[, base]) Returns the logarithm of x to
the given base. If base is omitted, this function computes the natural logarithm.
log10(x) Returns the base 10 logarithm of x.pow(x, y) Returns x** y. sqrt(x) Returns the square root of x. trunc(x) Truncates x to the nearest integer
towards 0.
30
Python Programming, 2/e31
Using the Math LibraryIn the textbook: writing a program to compute the roots of a
quadratic equation:
The only part of this we don’t know how to do is find a square root… but it’s in the math library.
2 4
2
b b acx
a
Python Programming, 2/e32
Using the Math Library To use a library, we need to make sure this
line is in our program:import math
Importing a library makes whatever functions are defined within it available to the program.
Python Programming, 2/e33
Using the Math Library To access the sqrt library routine, we need to
access it as math.sqrt(x)
Using this dot notation tells Python to use the sqrt function found in the math library module.
To calculate the root, you can dodiscRoot = math.sqrt(b*b – 4*a*c)
Math Library
Using the sqrt function is more efficient than using **. How could you use ** to calculate a square root?
Python Programming, 2/e35
The Limits of Int >>> import math >>> math.factorial(100) 933262154439441526816992388562667004
90715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
>>>
Wow! That’s a pretty big number! And Python can handle it….. can Java?
Python Programming, 2/e36
The Limits of Int What’s going on?
While there are an infinite number of integers, there is a finite range of ints that can be represented.
This range depends on the number of bits a particular CPU uses to represent an integer value.
Typical PCs use 32 bits.
Python Programming, 2/e37
The Limits of Int Typical PCs use 32 bits
That means there are 232 possible values, centered at 0.
This range then is –231 to 231-1. We need to subtract one from the top end to account for 0.
In 32-bit, the largest number that can be stored is 2147483647
Python Programming, 2/e38
The Limits of Int Can use floats, but then no longer get an
exact answer float(math.factorial(100)) 9.332621544394415e+157 lost after the 16th digit! float are approximations – the precision is fixed,
larger range
But 100! was fine ? how does it work in Python?
Python Programming, 2/e39
Handling Large Numbers: Long Int Very large and very small numbers are
expressed in scientific or exponential notation.
1.307674368e+012 means 1.307674368 * 1012
Here the decimal needs to be moved right 12 decimal places to get the original number, but there are only 9 digits, so 3 digits of precision have been lost.
Python Programming, 2/e40
Handling Large Numbers Python has a solution, expanding ints!
Python ints are not a fixed size and expand to handle whatever value it holds.
Python Programming, 2/e41
Handling Large Numbers Newer versions of Python automatically
convert your ints to expanded form when they grow so large as to overflow.
to do mathematical operations, Python breakers the expanded int into smaller pieces
We get indefinitely large values (e.g. 100!) at the cost of speed and memory
There is NO free lunch (ever)!!
More about libraries: random library Pseudo-random numbersimport random
randint(a,b) Returns a random integer, x, in the range a
<= x <= b.
random() Returns a random number in the range [0.0,
1.0).
42
Example program: Kiddymaths2import random #do this to use functions in random
def test():
start,stop=1,10
start2,stop2=1,10
dividend = random.randint(start,stop)
divisor = random.randint(start2,stop2)
intResult = dividend // divisor
remainder = dividend % divisor
print(dividend,"/", divisor, "=", intResult, "remainder", remainder)
test()
43
Improving “Kiddymaths”How do we ask the children for the answer and
check whether they are correct? Need SELECTION statements…
44
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 South Africa License.
45
Top Related