Previous Lecture Lecture 8 Next Lecture

Lecture 8, Thu 02/01

Sets, String Formatting cont, Binary Representation and Text

Recorded Lecture: 2_1_24

Sets

s1 = set() # create empty set
print(s1)
print(type(s1))
s1 = {1, 3, 5}
print(s1)
s1 = {1, 3, 5, 3, 1}
print(s1) # only stores unique items
intList = [1,2,3,4,5,4,3,2,1]
print(intList)
setList = set(intList)
print(setList)

Note on methods vs. functions

s = {2, 4, 6, 8}
print(s)
print(s.pop()) # removes and returns a random element
print(s)
print(s.add(10)) # adds an element but returns None
print(s)
s.add(10) # does nothing since 10 exists
print(s)
print(s.remove(6)) # removes 6 but returns None
print(s)

More on String formatting

print(f'{5*5=}')
x = 25
print(f'{x=}')
print(f'{x}=') # what would this be?
print(f'x={x=}') # and this?
print(f'x={x}') # and this?
course = "CSW8"
print(f'{course:s}') # s - string (not necessary)

value = 1234
print(f'{value:d}') # d - decimal (int)
print(f'{value:,d}') # ,d inserts commas
print(f'{value:05d}') # 0[int]d inserts leading 0's to create total [int] chars
print(f'{value:e}') # e - exponent notation
print(f'{value:.3f}') # 3 floating point numbers
print(f'{value:,.3f}') # 3 floating point numbers with commas

value = 12.34
#print(f'{value:s}') # error
#print(f'{value:d}') # error
print(f'{value:.4f}') # 12.3400
print(f'{value:e}') #1.234000e+01

Binary Number Representation

000 -> 0	100 -> 4
001 -> 1	101 -> 5
010 -> 2	110 -> 6
011 -> 3	111 -> 7
111 (base 2) = 1 * (2^2) + 1 * (2^1) + 1 * (2^0) = 7 (base 10)
101 (base 2) = 1 * (2^2) + 0 * (2^1) + 1 * (2^0) = 5 (base 10)
2510 (base 10) = 11001 (base 2)

___1___  | ___1___ | ___0___ | ___0___ | ___1___ 
2^4 (16) | 2^3 (8) | 2^2 (4) | 2^1 (2) | 2^0 (1)

25-16 = 9
9-8 = 1
1-1 = 0
8510 (base 10) = 1010101 (base 2)

___1____ | ____0___ | ___1___  | ___0___ | ___1___ | ___0___ | ___1___ 
2^6 (64) | 2^5 (32) | 2^4 (16) | 2^3 (8) | 2^2 (4) | 2^1 (2) | 2^0 (1)

85-64 = 21
21-16 = 5
5-4 = 1

Representing Text

print('a' == 'A') # False
print(ord('A')) #65
print(ord('a')) #97
print(chr(65)) # A
print(chr(97)) # a

Escape Characters

print("Python\nmakes\nme\nsmile!")
print("\t10\n\t20\n\t30")
print("10\\20\\30")
print("\"Hello!\"")
print("Won\'t stop, can\'t stop!")

Raw Strings

print(r"Python\nmakes\nme\nsmile!")
print(r"\t10\n\t20\n\t30")
print(r"10\\20\\30")
print(r"\"Hello!\"")
print(r"Won\'t stop, can\'t stop!")