Previous Lecture Lecture 2 Next Lecture

Lecture 2, Tue 10/02

Elements of simple programs in Python

Resources from lecture

Announcements:

Concept Questions

Today’s lecture:

Python as a calculator

Numerical type examples (type these in the shell to see what happens)


>>> 1

>>> 1+2

>>> 4/2

>>> 1/3

>>> 6/2

>>> 1/0

>>> 1+2*4

Storing data using variables

>>>x = 10 #What is the value of x?

>>>x = x * 10 # 10 * current value of x is stored back into x


More than just a calculator

x = 1
print(x)
print(type(x))

x = 4 / 2
print(x)
print(type(x))

y = 4 * 2
print(y)
print(type(y))

z = 4 * 2.0
print(z)
print(type(z))

x = "CS 8"
print(x)
print(x*2)

x = "8.0" # string not float
print(x) #8.0
print(type(x)) #str

print(x + 2) #ERROR
print(x + "2") # No error, uses concatenation

print(float(x) + 2) # No error, 10.0

x = "8.0" # Be careful ...
print(int(x)) #crashes

x = "8"
print(int(x))

x = "8.0"
y = "8.0"
z = "8.00"

print(x == y) #True
print(x == z) #False
print(float(x) == float(z)) #True
print(2 * 3 > 5) #True
print(type(2 * 3 > 5)) # bool

schoolName = "UCSB"
print(len(schoolName)) # 4
print(type(schoolName)) # str
print(schoolName[0])
print(schoolName[3])
#print(schoolName[4]) #ERROR
print(schoolName[-1]) # B - refers to the last index
#print(schoolName[-5]) # ERROR

#Extract a substring
print(schoolName[1:3]) # from position 1 up to (but not
                       # including) position 3
                       
# compute salary
hours = 40
rate = 10
salary = hours * rate
print("Salary is $", salary) # Notice quotes aren't displayed on the string in the outpout

Interacting with a program using print and input

# Example
print("Hi, please enter your name: ")
userName = input()
print("Hello", userName)


# We use something called ESCAPE CHARACTERS to print
# special characters including quotes.

print("\"Hi!\"") # \" is the double quote characters
print("Hi\nthere\n!") # \n is the newline character


# Another larger example
TAX_RATE = 0.1
print("Hi, please enter your name: ")
userName = input()
print("Hi", userName, ". What is the amount of your bill \
(not including tax and tip)?")
totalBill = float(input()) #be careful, will crash if not float
print("What is the tip percentage you would like to leave?")
tipPercentage = float(input())
taxAmount = totalBill * TAX_RATE
tipAmount = totalBill * (tipPercentage / 100)
print("The total amount to pay is $", totalBill + taxAmount + tipAmount)