Ha Khanh Nguyen  hknguyen
In this lecture, we will discuss:
# R code (not Python)
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
:
denotes the start of an indented code block.;
.#
to denote a comment in Python (just like R!).# initialize count
count = 0
for i in [1, 2, 3]:
# increase count
count = count + 1
a = [1, 2, 3]
b = a
list [1, 2, 3]
.a = 5
type(a)
int
a = 'foo'
type(a)
str
obj.attribute_name
or obj.method_name
..py
extension containing Python code.# some_module.py
PI = 3.14159
def f(x):
return x + 2
def g(a, b):
return a + b
some_module.py
:import some_module
result = some_module.f(5)
pi = some_module.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)
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 
Floordivide 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 EXCLUSIVEOR 

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 
is
is NOT the same as the ==
operator:a = [1, 2, 3]
b = a
c = list(a)
a is b
True
a is c
False
a == c
True
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
 TypeError Traceback (most recent call last) <ipythoninput83fb7f1898f95> in <module> 1 a_tuple = (3, 5, (2, 4)) > 2 a_tuple[1] = 2 TypeError: 'tuple' object does not support item assignment
This lecture note is modified from Chapter 2 of Wes McKinney's Python for Data Analysis 2nd Ed.