8
We will primarily use Google Colab for classroom demos.
We may also run Python on JupyterLab via Center for Integrated Research Computing (CIRC).
To request account, speak to your advisor if he/she has an account with CIRC; otherwise, contact Prof. McCall (DBCB students). This is optional.
Data types like boolean, integer, float, and strings (characters in R) are natively supported.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 1 ----> 1 print("hello I am " + age + " years old.") TypeError: can only concatenate str (not "int") to str
Ordered, mutatble collection of items (similar to R’s list).
Indexing and slicing:
[0.3, 5, -5, 9]
10
Ordered, immutatble collection of items.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[27], line 1 ----> 1 coord[0] = 10.0 # Immutable so we cannot modify in place. 2 print(coord) TypeError: 'tuple' object does not support item assignment
x = 3
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")
x is less than 5
Supports ternary operation:
Combine two or more lists into a list of tuples for iteration.
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
Alice is 25 years old.
Bob is 30 years old.
names = ["Alice", "Bob"]
ages = [25, 30]
net_assets = [1000000, 1000, 400000]
for name, age, net_asset in zip(names, ages, net_assets): # zip truncates to the length of the shorter list
print(f"{name} is {age} years old, and has ${net_asset}.")
Alice is 25 years old, and has $1000000.
Bob is 30 years old, and has $1000.
Iterate over the index and the item.
Generate new collection by iteration and optionally applying conditions/operations.
Functions without names, often used where short, disposable functionality is needed. Similar to anonymous functions in R’s apply
.
Starts with keyword with
to declare a opening of a resource such as file.
with open("example.txt", "w") as f:
f.write("Hello, Python!")
# File is closed and any resources released automatically without explicitly calling f.close()
f.write("Bye Python!") # Error.
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[56], line 6 2 f.write("Hello, Python!") 4 # File is closed and any resources released automatically without explicitly calling f.close() ----> 6 f.write("Bye Python!") ValueError: I/O operation on closed file.
Hello, Python!
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[57], line 4 1 with open("example.txt", "r") as f: 2 print(f.readline()) ----> 4 print(f.readline()) ValueError: I/O operation on closed file.
Class allows you to create your own data type made up of attributes (variables) and operations (functions).
self
: Refers to the instance on which the method is called.__init__
: A special method for initializing a new object, called constructor.self
as first argument.class Cat(Animal):
def __init__(self, name, sound):
print("Cat constructor.")
super().__init__(name)
self.sound = sound
def speak(self): # overriding parent's method
print(f"{self.name} {self.sound}")
def print_name(self):
print(self.name)
doug = Cat("Doug", "barks")
doug.print_name()
doug.speak()
Cat constructor.
Animal constructor.
Doug
Doug barks
class TestClass:
def __init__(self):
print("Class constructor.")
self.a = 5
self.dict = dict()
def add_to_dict(self, k, v):
# Divide v by self.a, then the resulting value to self.dict[k]
self.dict[k] = k / self.a
print("Added to dictionary.")
def get_item(self, k):
return self.dict[k]
obj = TestClass()
obj.add_to_dict(1, 5)
expected_value = 5 / obj.a
realized_value = obj.get_item(1)
print(f"Expected value: {expected_value}")
print(f"Realized value: {realized_value}") # Not what we expected.
Class constructor.
Added to dictionary.
Expected value: 1.0
Realized value: 0.2