Data Types

The idea of encapsulating data and operation in one object (at least, in Python)

ints Integers

In [2]:
x = 2 + 2
x
Out[2]:
4
In [19]:
result = input("Enter a value: ")
2 + int(result)
Enter a value: 42
Out[19]:
44

floats Floating Point Decimal Numbers

In [4]:
from math import pi
In [5]:
pi
Out[5]:
3.141592653589793
In [6]:
type(pi)
Out[6]:
float
In [7]:
pi * 10 + 42.42
Out[7]:
73.83592653589793
In [21]:
result = input("Enter a value: ")
2 + float(result)
Enter a value: 42.42
Out[21]:
44.42

complex Complex numbers (I never use them)

In [8]:
2 + 2j
Out[8]:
(2+2j)

bool Boolean values (True/False)

In [10]:
x = True
if x:
    print("it's obviously true!")
it's obviously true!
In [12]:
l = []
if l:
    print("The list is not empty")
else:
    print("The list is empty")
The list is empty
In [13]:
l = []
if l is True:
    print("The list is not empty")
else:
    print("The list is empty")
The list is empty
In [14]:
l = [1,2,3]
if l:
    print("The list is not empty")
else:
    print("The list is empty")
The list is not empty
In [15]:
bool([])
Out[15]:
False
In [16]:
bool(l)
Out[16]:
True
In [17]:
bool([4,5,6])
Out[17]:
True

Sequences

Lists, Tuples, Strings

In [29]:
l1 = [1,2,3]
l2 = [4,5,6]
l3 = l1 + l2
l3
Out[29]:
[1, 2, 3, 4, 5, 6]
In [30]:
t1 = (1,2,3)
t2 = (4,5,6)
t3 = l1 + l2
t3
Out[30]:
[1, 2, 3, 4, 5, 6]
In [31]:
s1 = "foo"
s2 = "bar"
s3 = s1 + s2
s3
Out[31]:
'foobar'
In [32]:
l1 * 3
Out[32]:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
In [33]:
l3[4]
Out[33]:
5
In [34]:
l3[2:5]
Out[34]:
[3, 4, 5]
In [35]:
len(l3)
Out[35]:
6
In [36]:
6 in l3
Out[36]:
True
In [37]:
42 in l3
Out[37]:
False

Variables

In [38]:
x = 0
In [39]:
id(x)
Out[39]:
4554333056
In [40]:
x = x + 7
In [42]:
id(x)
Out[42]:
4554333280
In [44]:
a,b,c = x,x,x
In [46]:
print(id(a),id(b),id(c),id(x))
4554333280 4554333280 4554333280 4554333280
In [47]:
z = 343_565
In [48]:
id(z)
Out[48]:
4602497520
In [49]:
z = z + 42
In [50]:
z
Out[50]:
343607
In [51]:
id(z)
Out[51]:
4602497328

Control Flow

"Decision Control"

  • if-elif-else
  • try-except-else-finally (exception handling)
  • for, whiles loops
In [54]:
try:
    x = "42.42"
    y = int(x)
except ValueError:
    print(f"The value {x} cannot be converted to an int!")  # f-strings, or string interpolation 3.6 or later?
The value 42.42 cannot be converted to an int!
In [55]:
def max1():
    x1, x2, x3 = eval(input("Please enter three values: "))
    
    if x1 >= x2 and x1 >= x3:
        _max = x1
    elif x2 >= x1 and x2 >=x3:
        _max = x2
    else:
        _max = x3
    
    print("The largest value is {0}".format(_max))
In [71]:
w = int("100")
x = 100
y = 1_000_000
z = 1_000_000
In [80]:
# Object (Value) Equality
x == w
Out[80]:
True
In [79]:
# Object Identity
x is w
Out[79]:
True
In [74]:
y == z
Out[74]:
True
In [75]:
y is z
Out[75]:
False
In [76]:
print(id(w), id(x))
4554336256 4554336256
In [77]:
print(id(y), id(z))
4603081968 4603082352
In [83]:
"1000000" == 1000000
Out[83]:
False
In [84]:
int("1000000") == 1000000
Out[84]:
True
In [85]:
x = 1000000000
In [86]:
x = 1_000_000_000
In [87]:
y = 3.1_41_59
In [88]:
y
Out[88]:
3.14159

Functions

In [91]:
from math import sqrt
In [94]:
def squareroot(n):
    root = n/2
    for k in range(20):
        root = (1.0/2)*(root + (n/root))
    return sqrt(n), root, sqrt(n)==root
In [97]:
squareroot(42)
Out[97]:
(6.48074069840786, 6.48074069840786, True)
In [100]:
print(dir(squareroot))
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
In [101]:
import math
In [103]:
print(dir(math))
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
In [104]:
2+2
Out[104]:
4
In [105]:
"foo" + "bar"
Out[105]:
'foobar'
In [108]:
(2).__add__(42)
Out[108]:
44
In [109]:
(2).__mul__(42)
Out[109]:
84

Classes

In [110]:
from random import randrange
In [1]:
class PlayingDie:
    def __init__(self, value=1):
        self.sides = 6
        self.value = value

    def roll(self):
        print(id(self))
        self.value = randrange(1, 7)
        
    def __repr__(self):
        return f"PlayingDie({self.value})"
In [136]:
list_of_dice = []
for i in range(10):
    list_of_dice.append(PlayingDie())

# Rolling all the dice to new value
for die in list_of_dice:
    die.roll()
In [137]:
list_of_dice
Out[137]:
[PlayingDie(3),
 PlayingDie(5),
 PlayingDie(4),
 PlayingDie(4),
 PlayingDie(6),
 PlayingDie(1),
 PlayingDie(6),
 PlayingDie(4),
 PlayingDie(5),
 PlayingDie(3)]
In [130]:
new_dice = [PlayingDie(1),
 PlayingDie(2),
 PlayingDie(2),
 PlayingDie(5),
 PlayingDie(1),
 PlayingDie(4),
 PlayingDie(5),
 PlayingDie(4),
 PlayingDie(1),
 PlayingDie(3)]
In [2]:
d = PlayingDie(3)
In [3]:
d
Out[3]:
PlayingDie(3)
In [4]:
d.roll()
4431697168
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-4-9b770f99a026> in <module>
----> 1 d.roll()

<ipython-input-1-c04eae4d9edb> in roll(self)
      6     def roll(self):
      7         print(id(self))
----> 8         self.value = randrange(1, 7)
      9 
     10     def __repr__(self):

NameError: name 'randrange' is not defined
In [5]:
d2 = PlayingDie(4)
In [6]:
d2.roll()
4432112912
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-a43cfd10b921> in <module>
----> 1 d2.roll()

<ipython-input-1-c04eae4d9edb> in roll(self)
      6     def roll(self):
      7         print(id(self))
----> 8         self.value = randrange(1, 7)
      9 
     10     def __repr__(self):

NameError: name 'randrange' is not defined