Python immutable and mutable objects
Some programming languages have a practice known as "pass by value" and "pass by reference" with respect to variables and functions. Passing a variable into a function “by value” means that a copy of the variable is passed into the function and if the value stored in the variable is changed within the function, the value is only changed in the copy of the variable and not the original variable. Passing by reference means the actual variable is passed into the function and, therefore, if the value stored in the variable is changed within the function, that change will be reflected in the variable back outside the function as well.
Python does not use the terms "pass by value" and "pass by reference". However, it does have the related practice of mutable or immutable objects. In practice, an immutable object act like passing by value and mutable objects act like passing by reference. In other words, if you pass an immutable object into a function, change its value, the change will not be reflected back in the main body of the program. If you pass a mutable object into a function, change its value, the change will be reflected back in the main body of the program. Numbers, strings and tuples are immutable. Dictionaries and lists are mutable.
In the example below, the variables num1 and num2 are assigned the values 2 and 3. The changeMe function is then called and their values (inside the function) changed to 4 and 5. However, after the function is over and the values stored in num1 and num2 are displayed, they are still 2 and 3. This is an example of pass by value and immutable objects.
Example: Passing an immutable object into a function
num1=2
num2=3
def changeMe(num1,num2):
num1=4
num2=5
print ("Inside the function: ", num1,num2)
changeMe(num1,num2)
print ("After the function: ", num1,num2)
Output:
Inside the function: 4 5
After the function: 2 3
In the next example, a list of two variables is created. Because a list is a mutable object, when the values in the list are changed, these changes are reflected outside and after the function is over. Lists will be discussed in more detail in the array chapter.
Example: Passing an mutable object into a function
num1=2
num2=3
nums=[num1,num2]
print ("Before the function: ", nums)
def changeMe(nums):
nums[0] = 4
nums[1] = 5
print ("Inside the function: ", nums)
changeMe(nums)
print ("After the function: ", nums)
Output:
Before the function: [2, 3]
Inside the function: [4, 5]
After the function: [4, 5]
Example: Mutable object example – Calling a function passing in a mutable object (list)
def addChecking(a, b):
print ("Your current checking and saving balance are: ", a)
a[0] = a[0] + b
bankAccounts = [540.34,1250.00]
addChecking(bankAccounts,100)
print ("Your new checking and saving balance are: ", bankAccounts)
Output:
Your current checking and saving balance are: [540.34, 1250.0]
Your new checking and saving balance are: [640.34, 1250.0]
Example: Mutable object example
def birthdays(ages):
ages = [26,24,32]
print ("Resulting ages: ", ages)
ages = [25,23,31]
print ("Initial ages: ", ages)
birthdays(ages)
Output:
Initial ages: [25, 23, 31]
Resulting ages: [26, 24, 32]
Example: Simple Tuition Calculator - Two Modules - One Argument (mutable pass by reference)
def listToStringWithoutBrackets(list1):
return str(list1).replace('[','').replace(']','')
def calculateAmountOwed(credits):
credits[0] = credits[0] * 100.00 + 50.00
amount_owed = 0
credits = float(input("How many credit hours will you be taking? "))
tuition2 = [credits]
calculateAmountOwed(tuition2)
tuition2 = listToStringWithoutBrackets(tuition2)
print("Your total tuition amount is $", tuition2, "dollars.")
floats = [float(x) for x in tuition2.split()]
print("Your total tuition amount is $%.2f dollars" % floats[0])
Output:
How many credit hours will you be taking? 2
Your total tuition amount is $ 250.0 dollars.
Your total tuition amount is $250.00 dollars
Example: Menu system with functions
menu_chosen = 0
# functions
def menu(menu_chosen):
print ("MAIN MENU")
print ("-----------------")
print ("1. Print pay checks")
print ("2. Look up employee")
print ("3. Change benefits")
print ("4. Exit")
menu_chosen = int(input("Chose menu option: "))
return menu_chosen
def print_pay():
print ("\nPRINT PAYCHECKS")
print ("---------------------")
return
def employee_lookup():
print ("\nEMPLOYEE LOOKUP")
print ("---------------------")
return
# main program
menu_chosen = menu(menu_chosen)
if menu_chosen == 1:
print_pay()
elif menu_chosen == 2:
employee_lookup()
Example: A function being called multiple times (data in, no data out)
def addNums(num1,num2):
total = num1+num2
print(num1, "+", num2, "=", total)
addNums(4,3)
addNums(15,6)
addNums(21,11)
addNums(115,333)
Output:
4 + 3 = 7
15 + 6 = 21
21 + 11 = 32
115 + 333 = 448
Example: A function being called multiple times (data in, no data out)
def getNum():
num=float(input("Enter number: "))
return num
num1=getNum()
num2=getNum()
num3=getNum()
total = num1+num2+num3
print(num1, "+", num2, "+", num3, "=", total)
Output:
Enter number: 12
Enter number: 4
Enter number: 2
12.0 + 4.0 + 2.0 = 18.0
Example: A function being called multiple times (data in, no data out)
def compForm(x,y):
result = (10 * x) + (5 * y)
print("Result:", result)
compForm(2,5)
compForm(3,4)
x=5
y=6
compForm(x,y)
Output:
Result: 45
Result: 50
Result: 80
Example: Word length function
def wordCheck(word):
length = len(word)
print("Your word is", length, "characters long.")
word = input("Enter a word: ")
wordCheck(word)
Example: Word length function - method #2
def wordCheck(word):
length = len(word)
return length
word = input("Enter a word: ")
length = wordCheck(word)
print("Your word is", length, "characters long.")
Output:
Enter a word: William
Your word is 7 characters long.
Example: Bowling Score Menu System
def menu():
print("1. Calculate average")
print("2. Exit\n")
choice = input("Enter choice: ")
return choice
def enterScores():
score1 = int(input("Enter score 1: "))
score2 = int(input("Enter score 2: "))
score3 = int(input("Enter score 3: "))
calcAverage(score1, score2, score3)
def calcAverage(score1, score2, score3):
average = (score1 + score2 + score3) / 3
print("The average is %.2f" % average)
def exit():
print("Goodbye")
choice = menu()
if choice == "1":
enterScores()
elif choice == "2":
exit()
Example: MPH to KPH Conversion
def mphtokph(mph):
kph = mph * 1.60934
print(mph, "equals %.0f" % kph)
mphtokph(25)
mphtokph(55)
mphtokph(70)
Output:
25 equals 40
55 equals 89
70 equals 113
Example: Functions for Math
def getNum():
num = int(input("Please enter number: "))
return num
def addNums(num1,num2):
result = num1 + num2
return result
num1 = getNum()
num2 = getNum()
result = addNums(num1,num2)
print(num1, "+", num2 ,"=", result)
Output:
Please enter number: 3
Please enter number: 4
3 + 4 = 7
Example: Functions call from a print statement
def greeting(name):
a = "Hello "+ name
return a
print(greeting("William"))
Output:
Hello William
Example: Functions call from an input statement
def greeting(name):
print("Hello "+ name)
greeting(input("What is your name? "))
Example: Calling a function from within a function
def getMess():
message = input("Enter your message: ")
printMess(message)
def printMess(message):
print(message)
getMess()
Output:
Enter your message: Hello
Hello
Example of Four Main Ways to Create User-Defined Function Related to Variables
Example: Meal Calculator: No Data In, No Data Out
def billCalc():
meal = float(input("Please enter your meal cost: "))
tip = float(input("Please enter your tip amount (e.g. .15 for 15%): "))
bill = meal + (meal * tip)
print("Your total bill comes to: $%.2f" % bill)
billCalc()
Output:
Please enter your meal cost: 100
Please enter your tip amount (e.g. .15 for 15%): .15
Your total bill comes to: $115.00
Example: Meal Calculator: Data In, No Data Out
def billCalc(meal, tip):
bill = meal + (meal * tip)
print("Your total bill comes to: $%.2f" % bill)
meal = float(input("Please enter your meal cost: "))
tip = float(input("Please enter your tip amount (e.g. .15 for 15%): "))
billCalc(meal,tip)
Example: Meal Calculator: Data In, Data Out
def billCalc(meal, tip):
bill = meal + (meal * tip)
return bill
meal = float(input("Please enter your meal cost: "))
tip = float(input("Please enter your tip amount (e.g. .15 for 15%): "))
bill = billCalc(meal,tip)
print("Your total bill comes to: $%.2f" % bill)
Example: Meal Calculator: No Data In, Data Out
def billCalc():
meal = float(input("Please enter your meal cost: "))
tip = float(input("Please enter your tip amount (e.g. .15 for 15%): "))
bill = meal + (meal * tip)
return bill
bill = billCalc()
print("Your total bill comes to: $%.2f" % bill)