Lists, Dictionaries, Iteration, and a Quiz
An proof of knowledge to show how to use Data Abstraction with Python Lists [] and Python Dictionaries {}.
- Lists and Dictionaries
- List and Dictionary purpose
- Using a For Loop
- Using a While Loop
- Using a Recursive Loop
- Time for a Quiz!
name = "Edwin A"
print("What is the variable value,", name)
import random
# variable of type string
name = "Edwin Abraham"
print("Name:", name, type(name))
age = 16 # Integer Type of Variable
print("age", age, type(age))
score = 104.1 # Float Type of Variable
print("score", score, type(score))
grade = 11 # Integer Type
print ("Grade Level:", grade, type(grade))
email = "edwinab0007@gmail.com"
print ("Email:", email, type(email))
print()
# Multiple variables in a single list and printing the whole list
langs = ["Python", "HTML", "CSS", "C", "R", "Lua", "Java"]
random_lang = random.choice(langs)
print("langs", langs, type(langs))
print("- langs[0]", langs[1], type(langs[1]))
print ("One Language:", random_lang)
foods = ["Burger", "Pizza", "Ice Cream", "Brownie,", "Paratha"]
random_car = random.choice(foods)
print("Food:", foods, type(foods) )
print("Random Food:", random_car)
print()
# variable of type dictionary (a group of keys and values)
person = { # Variable used later and helps store the data
"name": name,
"age": age,
"grade": grade,
"Language": langs,
"Email": email
}
print("person", person, type(person))
print('- person["name"]', person["name"], type(person["name"]))
InfoDb = []
# This is a list about my information and gives a list of this
InfoDb.append({
"FirstName": "Edwin",
"LastName": "Abraham",
"DOB": "August 7",
"Residence": "San Diego",
"Email": "edwinab0007@gmail.com",
"Hobbies": ["Biking","Hiking", "Playing Video Games"],
"Food": ["Burgers", "Pizza", "Brownies", "Watermelon"]
})
print()
print()
# This is another list about my partner in coding who is Emaad Mir
InfoDb.append({ # This bracket includes everything until the closed bracket
"FirstName": "Emaad",
"LastName": "Mir",
"DOB": "January 12",
"Residence": "San Diego",
"Email": "emaadidrismir@gmail.com",
"Hobbies": ["Playing Squash", "Sleeping", "Hiking", "Cooking", "Playing Basketball"],
"Food": ["French Fries", "Ice Cream", "Bananas", "Pizza"],
})
# Prints the data structure
print(InfoDb)
def print_data(person):
print("Name:", person["FirstName"], person["LastName"])
print("Birthday:", person["DOB"])
print("Email:", person["Email"])
print("Foods:", ", ".join(person["Food"]))
print("Hobbies:", ", ".join(person["Hobbies"]))
print()
print_data(InfoDb[0]) #This prints the variable with information from my data
print_data(InfoDb[1]) #This prints the code and the data from the previous lines from Emaad's data
def for_loop():
for person in InfoDb:
print_data(person)
def for_loop_with_index(): # prints out data depending on the length of the dictionary it comes from
for i in range(len(InfoDb)):
print_data(InfoDb[i])
print("Regular For Loop\n")
for_loop()
print("Indexed For Loop Output\n")
for_loop_with_index()
Using a While Loop
In coding, there are usually many ways to achieve the same result. Defined are functions illustrating using index to reference records in a list, these methods are called a "while" loop and "recursion".
- The while_loop() function contains a while loop, "while i < len(InfoDb):". This counts through the elements in the list start at zero, and passes the record to print_data()
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()
Using a Recursive Loop
This final technique achieves looping by calling itself repeatedly.
- recursive_loop(i) function is primed with the value 0 on its activation with "recursive_loop(0)"
- the last statement indented inside the if statement "recursive_loop(i + 1)" activates another call to the recursive_loop(i) function, each time i is increasing
- ultimately the "if i < len(InfoDb):" will evaluate to false and the program ends
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)
import getpass
Topic = ["Computer Science Principles", "Trivia", "Technology"]
Quiz = []
Quiz.append({
"When using [], what are you using?" : "Lists",
"Does .append allow you to add to a list? (T/F)" : "T",
"What file can you find the remote_theme and change it?" : "config.yml",
})
Quiz.append({
"What percent of people live in the northern hemisphere" : "90%",
})
Quiz.append ({
"What day is the Apple Far Out Event (mm-dd-yyyy)" : "09-07-2022",
})
def question_with_response(prompt):
print("Question " + ": " + prompt)
msg = input()
return msg
def for_loop_index():
score = [0, 0, 0]
s = 0
for topic in Quiz:
print("\ntopic: " + Topic[s])
for ques, ans in topic.items():
rsp = question_with_response(ques)
if rsp == ans:
print("Correct! You gain one point")
score[s] += 1
else:
print("Incorrect. This was the wrong answer, your score is the same")
s += 1
print()
print("Score in " + Topic[0] + ": " + str(score[0]) + " out of " + str(len(Quiz[0])))
print("Score in " + Topic[1] + ": " + str(score[1]) + " out of " + str(len(Quiz[1])))
print("Score in " + Topic[2] + ": " + str(score[2]) + " out of " + str(len(Quiz[2])))
return
print('Hello, ' + getpass.getuser() + " this is a quiz with 3 topics and 5 questions")
print("The First Topic is about Computer Science and then 1 question about Trivia and another about Technology")
for_loop_index()