Dr. Cho’s Website
Course Materials

Basic data types in Python

Institute for Environmental and Spatial Analysis...University of North Georgia

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

OperationMeaningResult type between integers
x + yAdditionint
x - ySubtractionint
x * yMultiplicationint
x / yDivisionfloat
x // yFloor divisionint
x % yModuloint
x ** yExponentint

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

AND01
000
101
OR01
001
111
XOR01
001
110
xNOT x
01
10

1.6   Bitwise operations

The bitwise operations are performed on bits.

OperationMeaning
x & yBitwise AND
x | yBitwise OR
x ^ yBitwise XOR
~xComplement
x << yShift x to the left by y places
x >> yShift 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

OperationResult
x and yy if x is truthy;
x otherwise
x or yx if x is truthy;
y otherwise
not xFalse 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

ComparisonMeaning
<less than
<=less than or equal to
>greater than
>=greater than or equal to
isobject identity
is notnegated 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))

Keywords: input, for, if, indexing, slicing, type casting, print