3. Data Types
Just a quick introduction to some basic data types in Python.
The Python Conceptual Hierarchy
Before we get to the code, let’s first establish a clear picture of how this chapter fits into the overall Python picture. From a more concrete perspective, Python programs can be decomposed into modules, statements, expressions, and objects, as follows:
- Programs are composed of modules.
- Modules contain statements.
- Statements contain expressions.
- Expressions create and process objects
Numbers:
Intergers: no fractional part
Floating-point numbers: with fractional part.
3.14e-2 # Scientific notation
123 + 222 # Integer addition
1.5 * 4 # Floating-point multiplication
2 ** 100 # 2 to the power 100
len(str(2 ** 1000000)) # How many digits in a really BIG number?
import math
print(math.pi)
print(math.sqrt(85))
The math
module contains more advanced numeric tools as functions, while the random
module performs random-number generation and random selections (here, from a Python list
coded in square brackets — an ordered collection of other objects to be introduced later):
import random
print(random.random())
random.choice([1, 2, 3, 4])
print('I\'m \"ok\".') # Use escape character \
print('I\'m learning\nPython.')
print('\\\n\\')
We could use r''
to avoid escape character:
print('\\\t\\')
print(r'\\\t\\')
Instead of \n
, we could use '''...'''
to display multiple lines.
print('''line1
... line2
... line3''')
True
False
3 > 2
3 > 5
Logical operators: and
, or
, not
True and True
True and False
False and False
5 > 3 and 3 > 1
True or True
True or False
False or False
5 > 3 or 1 > 3
not True
not False
not 1 > 2
We often use Boolean type in conditional statements:
if age >= 21:
print('Yes, you can.')
else:
print('Sorry.')
Precedence matters
General rule: arithmetic > comparison > not
> and
/or
Much more detailed operator precedence: https://docs.python.org/3/reference/expressions.html#operator-precedence
5 * 7 >= 3 + 5 * (7 - 1) and not False
35 >= 3 + 5 * 6 and not False
35 >= 3 + 30 and not False
35 >= 33 and not False
True and not False
True and True
True
a = 3
a + 2
a = a + 1.0
a
a = 3
b
a = 3
a == 5.0
a
b = 10
c = b > 9
c
5/2 == 5/2.0
2. For each of the following expressions, indicate the value returned. I encourage you to answer them directly since this will help reinforce your understanding of basic Python expressions.
3.0 - 1.0 != 5.0 - 3.0
3 > 4 or (2 < 3 and 9 > 10)
4 > 5 or 3 < 4 and 9 > 8
not(4 > 3 and 100 > 6)
3. The time module provides a function, also named time
, that returns the current Greenwich Mean Time in “the epoch”, which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.
import time
print(time.time())
Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch. You can only use time
module.