Basic data types in Python
1 Integers
The int
type can handle long integers very effectively.
x = 1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
type(x)
Integers are basically unbounded.
Only memory limits its maximum value.
1.1 Integer representations
You’re now familiar with these notations:
- Decimal:
53
- Binary:
0b110101
- Octal:
0o65
- Hexadecimal:
0x35
1.2 Binary integer operations
Operation | Meaning | Result type between integers |
---|---|---|
x + y | Addition | int |
x - y | Subtraction | int |
x * y | Multiplication | int |
x / y | Division | float |
x // y | Floor division | int |
x % y | Modulo | int |
x ** y | Exponent | int |
1.3 Floor division
x // y
is $\left\lfloor\frac{x}{y}\right\rfloor$.
4 // 3
4 // -3
-4 // 3
-4 // -3
1.4 Modulo
x % y
is $x - y\left\lfloor\frac{x}{y}\right\rfloor$.
4 % 3
4 % -3
-4 % 3
-4 % -3
1.5 Logic operations
AND | 0 | 1 |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
OR | 0 | 1 |
---|---|---|
0 | 0 | 1 |
1 | 1 | 1 |
XOR | 0 | 1 |
---|---|---|
0 | 0 | 1 |
1 | 1 | 0 |
x | NOT x |
---|---|
0 | 1 |
1 | 0 |
1.6 Bitwise operations
The bitwise operations are performed on bits.
Operation | Meaning |
---|---|
x & y | Bitwise AND |
x | y | Bitwise OR |
x ^ y | Bitwise XOR |
~x | Complement |
x << y | Shift x to the left by y places |
x >> y | Shift x to the right by y places |
1.7 Bitwise AND
01010111
& 01010000
----------
01010000
1.8 Bitwise OR
01010111
| 01010000
----------
01010111
1.9 Bitwise XOR
01010111
^ 01010000
----------
00000111
1.10 Complement
~ 01010111
----------
10101000
1.11 Left shift
<<2 01010111
------------
01011100
1.12 Right shift
>>2 01010111
------------
00010101
2 Floating-point numbers
The float
type represents floating-point (real) numbers.
Python’s float is a double-precision floating-point number, which occupies 64 bits or 8 bytes.
- Minimum non-zero value: Approximately
5e-324
- Maximum non-infinity value: Approximately
1.79e308
x = 5e-324
type(x)
x / 2 # underflow
y = 1.79e308
2 * y # overflow
All seven operations from the int
type are supported, but the result type is always float
.
3 Complex numbers
Use j
instead of i
for imaginary parts.
x = 4 + 5j
type(x)
y = 4 - 5j
z = x + y
type(z)
z.real
z.imag
The floor division (//
) and modulo (%
) operations are not supported. The result type is always complex
.
4 Strings
The str
type stores a sequence of characters.
a = 'Hello World!'
type(a)
print(a)
an_empty_string = ''
print('really'+an_empty_string+'?')
abc = "a\
b\
c\
"
print(abc)
4.1 String operations
The concatenation (+
) and repetition (*
) operations are supported.
'abcd' + '1234'
'abcd' * 10
4.2 Escape sequences
Escape sequences to include delimiters.
print("Single quote '")
print('Single quote \'')
print('Double quote "')
print("Dingle quote \"")
print("Backslash \\")
print("Enter\nTab\tTab")
print(r"Raw string literals do not translate escape sequences \'\"\\\n\t")
print(r"Raw string literals do not translate escape sequences \'"\\\n\t") # but not this!
4.3 Triple-quoted strings
Use three single/double quotes for multi-line strings.
a = '''No escaping needed for '!'''
b = """Even
"multiple"
lines"""
c = """
Maybe,
this is better?
"""
print(c) # c[1:-1] to remove extra new lines
4.4 Slicing strings
Extract characters from a string using slicing. Use a 0-based indexing scheme to access individual characters in a string. SOS and EOS stand for Start of String and End of String, respectively.
a = 'Hello World!'
a[0] # H
a[4] # o
a[0:4] # 0:4 => [0, 4) => Hell
a[0:5] # Hello
a[:5] # [SOS, 5) => Hello
a[0:-1] # [SOS to EOS-1) => Hello World
a[-6:-1] # [EOS-6, EOS-1) => World
a[-6:] # [EOS-6, EOS) => World!
a[::2] # every other characters
a[::-1] # backwards
a[::-2] # every other characters backwards
a[1:-1:3] # guess!
5 Boolean
The bool
type should be True
or False
, not true
or false
.
True
False
a = 'you'
type(a == 'you')
print(a == 'you')
5.1 True value testing
By default, an object is considered true unless its class defines either a
__bool__()
method that returns False or a__len__()
method that returns zero
Any expressions that are evaluated as True
in a boolean context (e.g., bool(1)
) are considered “truthy.” Otherwise (e.g., bool(0)
), they are “falsy.”
These built-in objects are considered falsy:
None
False
- Any numeric zero:
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- Empty sequences and collections:
""
,()
,[]
,{}
,set()
,range(0)
5.2 Boolean operations
Operation | Result |
---|---|
x and y | y if x is truthy;x otherwise |
x or y | x if x is truthy;y otherwise |
not x | False if x is truthy;True otherwise |
5.3 Short-circuiting
and
and or
are short-circuit operators where they stop evaluating the expression as soon as its truthiness or falsiness is logically determined.
The order of evaluation is from left to right.
x() and y() # if x() is falsy, this expression is already falsy and y() never gets evaluated
x() or y() # if x() is truthy, this expression is already truthy and y() never gets evaluated
5.4 Comparisons
Comparison | Meaning |
---|---|
== | equal to |
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
is | object identity |
is not | negated object identity |
5.5 is
and is not
The is
or is not
operators compare the memory addresses of two operands.
Do not use these operators to compare integers because Python returns a reference to an integer in $[-5, 256]$ instead of creating a new instance of the integer.
a = 256
a is 256 # True
a = 257
a is 257 # False
a = 3.14
a is 3.14 # True or False?
b = 3.14
a is b # True or False?
c = a
a is c # True or False?
6 Type casting
Type casting means converting one type of a variable to another.
x = '12'
type(int(x))
x = '12.34'
type(int(x)) # Oops!
x = 12.34
type(str(x))
7 Exercise: Read two integers
input
, type casting, print
Read two integer strings from the keyboard, cast them to two integers, add them, and print the sum.
x = int(input("x? "))
y = int(input("y? "))
print(x+y)
8 Exercise: User input and type casting
What does it do? What is the value of c
? Is it pre-determined or not? Why? For a
and b
, please type an integer only to make the code work. Also, try non-integer inputs like hello and see what happens.
a = int(input("a? "))
b = int(input("b? "))
c = a + b
print(c)
9 Exercise: Geospatial computation
What does this code do?
import math
x1 = float(input("x1? "))
y1 = float(input("y1? "))
x2 = float(input("x2? "))
y2 = float(input("y2? "))
d = math.sqrt((x1-x2)**2+(y1-y2)**2)
print(d)
10 Exercise: Understand input()
Now, you’ve tried three exercises and guess what the input()
function does and which data type it returns.
11 Exercise: Why type casting?
OK! Now, you figured out what the input()
function does and return, and how to use it. Let’s try this. Are both y
and z
the same or different? What are the data types of both variables and why?
x = "123"
y = 2 * x
z = 2 * int(x)