Previous Lecture Lecture 15 Next Lecture

Lecture 15, Tue 02/27

More on Functions, More on Strings

Recorded Lecture: 2_27_24

Mutable / immutable types as function parameters

def changeListParameter(x):
	x[0] = "!"
	print("inside changeListParamter:", x)
	return x

a = ["C","S","8"]
print(changeListParameter(a)) # ['!', 'S', '8']
print(a) # ['!', 'S', '8']

def changeStringParameter(x):
	x = x.replace("C", "!")
	print("inside changeStringParameter:", x)
	return x

b = "CS8"
print(changeStringParameter(b)) # !S8
print(b) # CS8

Default Parameter Values

def printMoney(amount=0.0, currency="dollars"):
	''' Function that takes an amount of money (float) and prints
	    out the amount and currency (str). '''
	print(f"{amount:.2f} {currency}")

printMoney() # 0.00 dollars (uses default parameters)
printMoney(12.5, "pesos") # 12.5 pesos (uses passed in parameter values)
printMoney(12.5) # 12.50 dollars (puts 12.5 in first parameter)
#printMoney("won") # error (puts won in first parameter, can't format a string)
printMoney(currency="won") # 0.00 won (uses default amount, currency set to won)

Mutable Default Parameters

def addElement(element, container=[]):
	container.append(element)
	return container

print(addElement(10)) # [10]
print(addElement(20)) # [10, 20] (still contains 10 from previous call

Functions Returning Multiple Values

x, y = 10, 20
print(x, y)
x, y, z = 10, 20, {30, 40}
print(x, y, z)
def getFullName():
	firstName = input("Enter first name: ")
	lastName = input("Enter last name: ")
	return firstName, lastName # packs into a tuple

first, last = getFullName()
print(first, last)

String Slicing

url = "https://www.ucsb.edu/"

# Get everything EXCEPT the last character
print(url[0:20]) # https://www.ucsb.edu
print(url[:-1]) # https://www.ucsb.edu

# get http
print(url[:4]) # http
# reverse url
print(url[-1:-22:-1]) # /ude.bscu.www//:sptth

print(url) # https://ucsb.edu/ (slicing only returns copies of the substring)

String Methods

s = "one two three la la la"

print(s.replace("one", "1")) # 1 two three la la la
print(s) # one two three la la la

print(s.replace("la", "LA")) # one two three LA LA LA

s = s.replace("la", "LA", 2)  # s is reassigned
print(s) # one two three LA LA la