In this lecture, we will discuss:


1. Indentations, not braces

a = 10
if (a < 5) {
  result = TRUE
  b = 0
} else {
  result = FALSE
  b = 100
}
a = 10
if a < 5:
    result = True
    b = 0
else:
    result = False
    b = 100

2. Everything is an object


3. Comments in Python

# initialize count
count = 0

for i in [1, 2, 3]:
    # increase count
    count = count + 1

4. Variables and arguments passing

a = [1, 2, 3]
b = a


5. Dynamic references, strong types

a = 5
type(a)
## <class 'int'>
a = 'foo'
type(a)
## <class 'str'>

6. Attributes and methods


7. Imports

# some_module.py
PI = 3.14159

def f(x):
  return x + 2
  
def g(a, b):
  return a + b

If we want to access the variables and functions defined in some_module.py:

import some_module

result = some_module.f(5)
pi = some_module.PI

Or

from some_module import f, g, PI

result = g(f(5), PI)

Or

import some_module as sm
from some_module import PI as pi, g as gf

r1 = sm.f(pi)
r2 = gf(r1, pi)

8. Binary operators and comparisons

Operation Description
a + b Add a and b
a - b Substract b from a
a * b Multiply a by b
a / b Divide a by b
a // b Floor-divide a by b, dropping any fractional remainder
a ** b Raise a to the b power
a & b True if both a and b are True; for integers, take the bitwise AND
a | b True if either a or b is True; for integers, take the bitwise OR
a ^ b True if a is True or b is True, BUT NOT BOTH; for integers, take the bitwise EXCLUSIVE-OR
a == b True if a equals b
a != b True if a is not equal to b
a <= b, a < b True if a is less than (less than or equal) to b
a >= b, a > b True if a is greater than (greater than or equal) to b
a is b True if a and b reference the same Python object
a is not b True if a and be references different Python objects
a = [1, 2, 3]
b = a
c = list(a)
a is b
## True
a is c
## False
a == c
## True

9. Mutable and immutable objects

a_list = ['foo', 2, [4, 5]]
a_list[2] = (3, 4)
a_list
## ['foo', 2, (3, 4)]
a_tuple = (3, 5, (2, 4))
a_tuple[1] = 2
## Error in py_call_impl(callable, dots$args, dots$keywords): TypeError: 'tuple' object does not support item assignment
## 
## Detailed traceback: 
##   File "<string>", line 1, in <module>

This lecture note is modified from Chapter 2 of Wes McKinney’s Python for Data Analysis 2nd Ed.