Instructor: David Cao (davidcao@seas) TAs: Chris Liu (liuchris@seas) Pragya Singh (pragya7@wharton)
# Isn't Python great?print("Hello, World!")
// Javaclass HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); }}
// Gopackage mainimport "fmt"func main() { fmt.Println("Hello, World!")}
// C++#include <stdio.h>int main() { printf("Hello, World!"); return 0;}
// rustfn main() { println!("Hello World!");}
There are two ways of running Python. Either we can invoke Python directly within it's interpreter, or we can write files with our Python code.
❯ pythonPython 3.10.12 (main, Jan 18 2024, 12:41:08) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwinType "help", "copyright", "credits" or "license" for more information.>>>
>>> 5 + 1015>>> 5 ** 225>>> my_var = "Hello, World!">>> print(my_var)Hello, World!>>>
If you've written your Python in a file, you can simply run it like so
❯ echo "print('Hello, World!')" > my_script.py❯ python my_script.pyHello, World!
my_object = MyClass()my_object.do_something()
def my_func(a, b, c): ...# functions themselves are objects!print(my_func)# prints out: <function my_func at 0x102aad990>
# my incredibly insightful comment"""a really long and more insightfulcomment that needs multiple lines"""print("Hello, World!")
>>> my_var = 10 # no type declaration needed!>>> type(my_var)int>>> my_var = "hello!">>> type(my_var)str>>> my_var = 10>>> str(my_var)"10">>> print(my_var) # print casts everything to a str implicitly>>> my_var = "10">>> int(my_var)10>>> my_var = None # None is Python's null>>> type(my_var)NoneType>>> type(type(my_var)) # every type is type type :)type
# note the : token to indicate a scopeif x > 15: print("x is larger than 15")elif x < 15: print("x is less than 15")else: print("x is exactly 15")# this could also be written asif x > 15: print("x is larger than 15")elif x < 15: print("x is less than 15")else: print("x is exactly 15")# but I don't recommend it as it looks messy# however, these are useful as one-line control statementsy = "gt" if x > 15 else "lte"
i = 0# again note the : token and indentationwhile i < 10: print(i) i += 1# there is no do-while in Python, insteadwhile True: do_something() if condition: break # exit loop
for i in range(0,10): print(i)for i in range(0,10): if i % 2 == 0: # skip below code and continue loop continue print(i)
# functions are defined using the "def" keyword# once again, we see our good friend :def my_func(x): return x + 5def my_func(x): # you can stub out functions with the pass keyword # my_var = my_func(x) # will result in my_var = None pass
We will revisit functions later to see the power of Python's functional attributes!
# two ways to instantiate listsl = list()l = list([1,2,3,4,5]) # this is actually a cast!l = []l = [1,2,3,4,5]# retrieving elements is easyl[0] # 1l[-1] # 5# we can slice a listl[1:3] # [2,3,4]l[1:] # [2,3,4,5]l[:3] # [1,2,3]len(l) # length of object# a neat trick to instantiate a listl = [0] * 5 # [0,0,0,0,0]
l = [1,2,3]# adds an element to end of listl.append(5) # [1,2,3,5]# adds element at the specified indexl.insert(3, 4) # [1,2,3,4,5]l.append("6") # lists can contain multiple types!elem = l.pop() # remove and return last elementelem = l.pop(2) # remove and return element at index# remove first occurrence of given elementl.remove("thing_to_remove")# we can concat two lists easilyl + [6,7,8]l.extend([6,7,8])l.extend((6,7,8)) # extend takes any iterable
students = ["David", "Ben", "Justin"]# iteration is done using "for _ in _:"for s in students: print(s)# you can still do this if you wantfor i in range(0, len(s)): s = students[i] print(s)# but this is more pythonicfor i, s in enumerate(students): print(i, s)
numbers = [7, 4, 12, 20, 16, 1]# sorted() returns a sorted copy of the original listsorted(numbers)[0] # 1numbers[0] # still 7# we can sort in-place as wellnumbers.sort()numbers[0] # 1# sorted descending order is easysorted(numbers, reverse=True)numbers.sort(reverse=True)
model = "civic"make = "honda"car = (model, make) # note regular parenscar = model, make # this also works# tuple deconstruction is very niceyear, model, make = 2020, "civic", "honda"# tuple indexing is the same as listscar[0]car[0:2]# neat trick, we can swap variables easilyx, y = 1, 2x, y = y, x# same trick as lists works toot = (0) * 3
car[0] = "accord"
# instantiate a set in two waysstudents = set()students = {"David", "Ben", "Justin"}# adding and removing elementsstudents.add("Chris") students.remove("David")# checking existencedavid_exists = "David" in studentsif "David" not in students: print("David is not a student")
naturals = {0,1,2,3,4,5,6,7}primes = {2,3,5,7}# intersectionnaturals.intersection(primes)naturals & primes# unionnaturals.union(primes)naturals | primes# differencenaturals.difference(primes)naturals - primes
Strings can be thought of as a data structure themselves (a list!)
s = "my very long string"# indexing/slicing is the same as listss[0] # "m"s[:7] # "my very"# a python tricks[::2] # "m eyln tig", every 2nd element# every -1 element, i.e. reverseds[::-1] # "gnirts gnol yrev ym"
# checking substringsif "long" in s: print("string contains 'long'")
__iter__()
__next__()
l
copy
deepcopy
l = [1,2,3]l2 = ll[0] = 100 # both l and l2 are mutated!print(l, l2) # [100,2,3] [100,2,3]from copy import copy, deepcopyl = [1,2,[3,4]]l2 = copy(l)l[2][0] = 100print(l, l2) # [1,2,[100,4]] [1,2,[100,4]]l = [1,2,[3,4]]l2 = deepcopy(l)l[2][0] = 100print(l, l2) # [1,2,[100,4]] [1,2,[3,4]]
# instatiationattendance = dict()attendance = {"David": 5, "Ben": 4}# setting and gettingattendance["Justin"] = 5# removing elementdel attendance["Ben"]
defaultdict
if "Sara" not in attendance: # not fun :( attendance["Sara"] = 0attendance["Sara"] += 1from collections import defaultdictwords = [ "some", "words", "to", "be", "counted", "some", "more", "words",]count = defaultdict()for w in words: # much nicer! count[w] += 1# defaultdict uses 0 by default, but we can specify the typedefaultdict(str)
__init__()
# define using "class" reserved wordclass Car: pass# to instantiate objectcar = Car()# note that we don't even need setter/getter methods!car.model = "civic"car.make = "honda"# we can explicitly require these in the constructorclass Car: def __init__(self, model, make): # note the similarity of `self` and `this` in Java self.model = model self.make = make
Student(Person, OtherClass)
name
Person
__init__
Student
class Person: def __init__(self, name): self.name = name def say_hello(self): print(f"Hi my name is {self.name}!")class Student(Person): def __init__(self, name, grade): Person.__init__(self, name) self.grade = grade def study(self): self.grade = min(100, self.grade + 10) print(f"{self.name} studied and " + f"their grade is now {self.grade}!")s = Student("David", 50)s.say_hello()s.study()