Python Datatypes#

Integers#

  • In Python 2, there was an internal limit to how large an integer value could be. But that limit was removed in Python 3. > This means there is no explicitly defined limit, but the amount of available address space forms a practical limit depending on the machine Python runs on.

[20]:
# express the constant floating-point value 3.2 × 10-12 in Python:
print('large float =>',3.2e-12)
large float => 3.2e-12

Floats#

  • Internal representation of float objects is not precise, so they can’t be relied on to equal exactly what you think they will

[3]:
# Do not use '==' operator to compare two floats
print(1.1 + 2.2 == 3.3)
# Use Tolerance
tolerance = 0.00001
abs((1.1 + 2.2) - 3.3) < tolerance
False
[3]:
True

Strings#

  • immutable

Raw Strings#

  • A raw string literal is preceded by r or R, which specifies that escape sequences in the associated string are not translated. The backslash character is left in the string:

[21]:
print(r'foo\\bar\n')

foo\\bar\n

Boolean#

  • All the following are considered false when evaluated in Boolean context:

    • The Boolean value False

    • Any value that is numerically zero (0, 0.0, 0.0+0.0j)

    • An empty string

    • An object of a built-in composite data type which is empty (see below)

    • The special value denoted by the Python keyword None

  • Virtually any other object built into Python is regarded as true.

[8]:
# Numeric
print(bool(0), bool(0.0), bool(0.0+0j))
# String
print(bool(''), bool(""), bool(""""""))
# Composite, like list
print(bool([]))
# Nested: Here the list has an element, so it is True
print(bool([[]]))
False False False
False False False
False
True
4.4
[11]:
# Comparison
x = 0.0
y = 4.4
print('or:',x or y)
print('and:',x and y)

or: 4.4
and: 0.0

Compund Logic & Short-Circuit Evaluation#

Consider following compound logic: x1 or x2 or x3 or … xn

Short Circuit Evaluation - The xi operands are evaluated in order from left to right. As soon as one is found to be true, the entire expression is known to be true. At that point, Python stops and no more terms are evaluated. The value of the entire expression is that of the xi that terminated evaluation.

[14]:
# Use Case example, the error is avoided in this example.
a = 0
b = 1
# (b / a) > 0 #ZeroDivisionError: division by zero
a != 0 and (b / a) > 0 # ShortCircuit evaluation, the second part is not evaluated if the first part is False

[14]:
False

Truthy (and / or) Falsy#

If a is

a or b is

a and b is

truthy

a

b

falsy

b

a

[18]:
a = 100
b = 200
print('or =>', a or b)
print('and =>', a and b)
or => 100
and => 200
[34]:
# True = False
# while True:
#     print(True)
#     break

# for i in range(float('inf')):
#     print(i)

d = {'a':1, 'b':2}
for i in d:
    print(i)

t = ('a',1)
print(t*2)

s = 'Hello'
print(s[-1:]) # [Start:-1:Stop:end,stride:1]
print(s[-2:])
print(s[-4:])
a
b
('a', 1, 'a', 1)
o
lo
ello
[ ]: