Loops, Dictionaries, and Lists
Testing out different loops in combination with lists and dictionaries
- For Loop Test
- While Loop Test
- Recursive Loop Test
- Reversed List
- Randomized List
- Random Grocery List Generator
- Quiz using lists
InfoDb = []
# Data structure with keys and values
# Append to list a Dictionary of key/values related to a person and their hobbies
InfoDb.append({
"FirstName": "Aiden",
"LastName": "Huynh",
"DOB": "May 12",
"Residence": "Escondido",
"Email": "ah5993909@gmail.com",
"Hobbies": ["Gaming", "Video Editing"]
})
# Append a 2nd dictionary
InfoDb.append({
"FirstName": "Avinh",
"LastName": "Huynh",
"DOB": "December 27",
"Residence": "Escondido",
"Email": "avinhahuynh@gmail.com",
"Hobbies": ["Gaming", "Streaming"]
})
# Prints all of the dictionary values
def print_data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"]) # comma adds space between two values
print("\t", "Residence:", d_rec["Residence"]) # \t adds an indent
print("\t", "Birth Day:", d_rec["DOB"])
print("\t", "Hobbies: ", end="")
print(", ".join(d_rec["Hobbies"]))
print()
# Loop algorithm
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record)
for_loop()
While Loop Test
This algorithm only loops while a certain condition is met. In this case, it will only loop while the variable "i" is less than the number of items in the list given by the len command. The way we make this function is by adding one to "i" at the end of each loop, making it increase by one for each cycle until eventually becoming equal to the number of items in the list, thus ending the loop.
InfoDb = []
# Data structure with keys and values
# Append to list a Dictionary of key/values related to a person and their hobbies
InfoDb.append({
"FirstName": "Aiden",
"LastName": "Huynh",
"DOB": "May 12",
"Residence": "Escondido",
"Email": "ah5993909@gmail.com",
"Hobbies": ["Gaming", "Video Editing"]
})
# Append a 2nd dictionary
InfoDb.append({
"FirstName": "Avinh",
"LastName": "Huynh",
"DOB": "December 27",
"Residence": "Escondido",
"Email": "avinhahuynh@gmail.com",
"Hobbies": ["Gaming", "Streaming"]
})
# Prints all of the dictionary values
def print_data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"]) # comma adds space between two values
print("\t", "Residence:", d_rec["Residence"]) # \t adds an indent
print("\t", "Birth Day:", d_rec["DOB"])
print("\t", "Hobbies: ", end="")
print(", ".join(d_rec["Hobbies"]))
print()
# While Loop -> While a specified condition is met (i < len(InfoDb)), it will loop
def while_loop():
print("While loop output\n")
i = 0
while i < len(InfoDb):
record = InfoDb[i]
print_data(record)
i += 1
return
while_loop()
InfoDb = []
# Data structure with keys and values
# Append to list a Dictionary of key/values related to a person and their hobbies
InfoDb.append({
"FirstName": "Aiden",
"LastName": "Huynh",
"DOB": "May 12",
"Residence": "Escondido",
"Email": "ah5993909@gmail.com",
"Hobbies": ["Gaming", "Video Editing"]
})
# Append a 2nd dictionary
InfoDb.append({
"FirstName": "Avinh",
"LastName": "Huynh",
"DOB": "December 27",
"Residence": "Escondido",
"Email": "avinhahuynh@gmail.com",
"Hobbies": ["Gaming", "Streaming"]
})
# Prints all of the dictionary values
def print_data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"]) # comma adds space between two values
print("\t", "Residence:", d_rec["Residence"]) # \t adds an indent
print("\t", "Birth Day:", d_rec["DOB"])
print("\t", "Hobbies: ", end="")
print(", ".join(d_rec["Hobbies"]))
print()
# Recursive Loop -> keeps incrementing on each call (n+1) until exit condition is met
def recursive_loop(i):
if i < len(InfoDb):
record = InfoDb[i]
print_data(record)
recursive_loop(i + 1)
return
print("Recursive loop output\n")
recursive_loop(0)
GList = [
["Apple", "1.32"],
["Orange", "1.45"],
["Banana", "0.62"],
["Strawberry", "0.11"],
["Blueberry", "0.02"],
["Pineapple", "2.18"],
["Watermelon", "4.98"],
["Kiwi", "1.07"],
["Mango", "1.32"],
["Grape", "0.03"]
]
# Reverses the list
GList.reverse()
print(GList)
import random
# Imports various commands for randomization
# List of fruits and their prices
GList = [
["Apple", "1.32"],
["Orange", "1.45"],
["Banana", "0.62"],
["Strawberry", "0.11"],
["Blueberry", "0.02"],
["Pineapple", "2.18"],
["Watermelon", "4.98"],
["Kiwi", "1.07"],
["Mango", "1.32"],
["Grape", "0.03"]
]
# Randomizes (shuffles) the list
random.shuffle(GList)
print(GList)
import random
# List of fruits and their prices
GList = [
["Apple", "1.32"],
["Orange", "1.45"],
["Banana", "0.62"],
["Strawberry", "0.11"],
["Blueberry", "0.02"],
["Pineapple", "2.18"],
["Watermelon", "4.98"],
["Kiwi", "1.07"],
["Mango", "1.32"],
["Grape", "0.03"]
]
print("Input the desired number of fruits (esc to cancel):")
fruitCount = input() # Prompts user on the desired amount of fruits
# k defines the number of fruits to pull, and by setting that equal to the input(), we pull only the amount desired by the user
selectedPairs = random.choices(GList, k=int(fruitCount))
# int() is used because k must be an integer, did not do this in line 18 because input() must be a string to be printed
print("You selected "+fruitCount+" fruits:")
# This section defines the first term as the fruit and second as the corresponding price, allowing us to use each part separately
for pricePair in selectedPairs:
fruit = pricePair[0]
price = pricePair[1]
print(fruit+": $"+price)
# Calculates the sum of the prices
n = float(price)
sum = sum+n
total = round(sum, 2)
print("Your total is: $"+str(total))
sum = 0