In this part of the Learn to Program tutorial series we will look at Dictionaries and one of the most confusing topics in programming being Recursive Functions. A Recursive Function is a function that calls for itself to execute. We’ll generate Factorials and Fibonacci numbers with recursive functions to help make them make more sense.
All of the commented code follows the video below.
If you like videos like this consider contributing a dollar on Patreon.
[googleplusone]
Code & Transcript
# ---------- LEARN TO PROGRAM 7 ----------
# ---------- DICTIONARIES ----------
# While lists organize data based on sequential indexes
# Dictionaries instead use key / value pairs.
# A key / value pair could be
# fName : "Derek" where fName is the key and "Derek" is
# the value
# Create a Dictionary about me
derekDict = {"fName": "Derek", "lName": "Banas", "address": "123 Main St"}
# Get a value with the key
print("May name :", derekDict["fName"])
# Change a value with the key
derekDict["address"] = "215 North St"
# Dictionaries may not print out in the order created
# since they are unordered
print(derekDict)
# Add a new key value
derekDict['city'] = 'Pittsburgh'
# Check if a key exists
print("Is there a city :", "city" in derekDict)
# Get the list of values
print(derekDict.values())
# Get the list of keys
print(derekDict.keys())
# Get the key and value with items()
for k, v in derekDict.items():
print(k, v)
# Get gets a value associated with a key or the default
print(derekDict.get("mName", "Not Here"))
# Delete a key value
del derekDict["fName"]
# Loop through the dictionary keys
for i in derekDict:
print(i)
# Delete all entries
derekDict.clear()
# List for holding Dictionaries
employees = []
# Input employee data
fName, lName = input("Enter Employee Name : ").split()
employees.append({'fName': fName, 'lName': lName})
print(employees)
# ---------- PROBLEM : CREATE A CUSTOMER LIST ----------
# Create an array of customer dictionaries
# Output should look like this
'''
Enter Customer (Yes/No) : y
Enter Customer Name : Derek Banas
Enter Customer (Yes/No) : y
Enter Customer Name : Sally Smith
Enter Customer (Yes/No) : n
Derek Banas
Sally Smith
'''
# Create customer array outside the for so it isn't local
# to the while loop
customers = []
while True:
# Cut off the 1st letter to cover if the user
# types a n or y
createEntry = input("Enter Customer (Yes/No) : ")
createEntry = createEntry[0].lower()
if createEntry == "n":
# Leave the while loop when n is entered
break
else:
# Get the customer name by splitting at the space
fName, lName = input("Enter Customer Name : ").split()
# Add the dictionary to the array
customers.append({'fName': fName, 'lName': lName})
# Print out customer list
for cust in customers:
print(cust['fName'], cust['lName'])
# ---------- RECURSIVE FUNCTIONS ----------
# A function that refers to itself is a recursive function
# Calculating factorials is commonly done with a recursive
# function 3! = 3 * 2 * 1
def factorial(num):
# Every recursive function must contain a condition
# when it ceases to call itself
if num <= 1:
return 1
else:
result = num * factorial(num - 1)
return result
print(factorial(4))
# 1st : result = 4 * factorial(3) = 4 * 6 = 24
# 2nd : result = 3 * factorial(2) = 3 * 2 = 6
# 3rd : result = 2 * factorial(1) = 2 * 1 = 2
# ---------- PROBLEM : CALCULATE FIBONACCI NUMBERS ----------
# To calculate Fibonacci numbers we sum the 2 previous
# values to calculate the next item in the list like this
# 1, 1, 2, 3, 5, 8 ...
# The Fibonacci sequence is defined by:
# Fn = Fn-1 + Fn-2
# Where F0 = 0 and F1 = 1
'''
Sample Run Though to Help
print(fib(3))
# 1st : result = fib(2) + fib(1) : 2 + 1
# 2nd : result = (fib(1) + fib(0)) + (fib(0)) : 1 + 0
# 3rd : result = fib(2) + fib(1)
print(fib(4))
# 1st : result = fib(3) + fib(2) : 3 + 2
# 2nd : result = (fib(2) + fib(1)) + (fib(1) + fib(0)) : 2 + 1
# 3rd : result = (fib(1) + fib(0)) + fib(0) : 1 + 0
'''
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
result = fib(n-1) + fib(n-2)
return result
print(fib(3))
print(fib(4))