Previous Lecture Lecture 10 Next Lecture

Lecture 10, Thu 02/08

Functions cont., While Loops

Recorded Lecture: 2_8_24

Dynamic Typing

x = 10 # x refers to an int type
x = "10" # x refers to a str type
def tripleParam(value):
	''' Triples the parameter value, and returns the tripled value '''
	return value + value + value

print(tripleParam(4)) # 12
print(tripleParam("4")) # 444
def tripleParam(value):
	''' Returns the triple of parameter value '''
	if type(value) == str: # explicitly check if value is a str
		value = int(value) # convert it to an int if necessary

	return value + value + value

Calling Functions in Expressions

def multiply(x, y):
	''' Returns the product of the parameters x and y '''
	return x * y

print(multiply(3,3)) # 9
print(multiply('4', 4)) # 4444
#print(multiply('4','4')) # Error

def cube(num):
	''' Returns the cube of parameter num '''
	return multiply(num, num) * num

print(cube(2)) # 8
print(cube(3)) # 27

Functions as Objects

print(type(cube)) # function
def compute(someFunction, value):
	return someFunction(value) # someFunction referring to the function passed in

userValue = int(input("Enter an integer: "))
userChoice = input("Enter 1 to triple. Enter 2 to cube: ")

if userChoice == "1":
	print(compute(tripleParam, userValue))
if userChoice == "2":
	print(compute(cube, userValue))

Variable Scope

def myFunction():
	name = "CSW8"
	print(name)
	return

myFunction()
print(name) # Error, name variable only exists in myFunction
x = 100

def myFunction(x):
	print(x)

myFunction("CSW8") # No error, but what gets printed?

While Loops

Syntax:
while BOOLEAN_EXPRESSION:
	STATEMENT(S)


If BOOLEAN_EXPRESSION is true, perform statements in the body of the loop. Then check if BOOLEAN_EXPRESSION is True
or False (and repeat)
If BOOLEAN_EXPRESSION is false, skip the body of loop entirely and continue execution.
# cntrl-c will terminate execution
while True:
	print("Weeee!")
num = 1
while num <= 10:
	print("num =", num)
	num += 1
value = input("Enter STOP: ")
while value != "STOP":
	print(f"You didn't do what I wanted! You typed '{value}'. Try again")
	value = input("Type STOP: ")

print(f"Hooray! You typed '{value}'!")
import random

rollDie1 = 0
rollDie2 = 0
numRolls = 0
while (rollDie1 + rollDie2) != 12:
	numRolls += 1
	rollDie1 = random.randint(1,6)
	rollDie2 = random.randint(1,6)
	print(f"({rollDie1},{rollDie2}) = {rollDie1 + rollDie2}")

print("Congrats! You rolled a 12!")
print(f"It took {numRolls} attempts")