Previous Lecture Lecture 3 Next Lecture

Lecture 3, Tue 01/16

Expressions, Modules

Recorded Lecture: 1_16_24

A note about signing up for Gradescope

Objects and Types

print(id(100))
print(id(3.6))

(Brief) Introduction to String Formatting (f-strings)

TAX_RATE = 0.1
userName = input("Hi, please enter your name: ")

print("Hi,", userName, ". What’s the amount of your bill (not including tax and tip)?")
totalBill = float(input()) #take the input() string and convert it to a float.

print("What tip percentage would you like to leave?")
tipPercentage = float(input())

taxAmount = totalBill * TAX_RATE
tipAmount = totalBill * (tipPercentage / 100)
print("The total amount to pay is $", totalBill + taxAmount + tipAmount)
The total amount to pay is $ 130.0
x = 130.0
print(f"${x}") #$130.0
x = 130.0
print(f"${x:.2f}") #$130.00
x = 130.1299
print(f"${x:.2f}") #$130.13
print(f"The total amount to pay is ${(totalBill + taxAmount + tipAmount):.2f}")

Syntax vs. Runtime Errors

print("Start")

PYTHON!

print( Hello )
print("Start")
print( Hello )
Traceback (most recent call last):
  File "/Users/richert/Desktop/UCSB/CS9/lecture.py", line 5, in <module>
    print( Hello )
NameError: name 'Hello' is not defined

Compound Operators

x += 1 #equivalent to x = x + 1
x -= 5 #equivalent to x = x - 5
x *= 2 #equivalent to x = x * 2
x /= 4 #equivalent to x = x / 4
x %= 3 #equivalent to x = x % 3

Modules

# myModule.py
name = "Richert"
course = "CMPSCW8"
print(name, course)
# lecture.py
import myModule # Name of the file to import (without .py)

print("In lecture.py script")
print(myModule.name)
print(myModule.course)

if __name__ == '__main__':

# myModule.py
name = "Richert"
course = "CMPSCW8"

if __name__ == '__main__':
	print(name, course)
# myModule.py

if __name__ == '__main__':
	name = "Richert"
	course = "CMPSCW8"
	print(name, course)