Lists, Dictionaries, Iteration Notes
Some notes on how python works.
- Types of Variables in Python
- Lists and Dictionaries
- Formatting List/Dictionary (With For Loop)
- Other Ways to Loop - while_loop
- Repeating a Function - Recursion
- Hacks Questions
- Python Quiz Using Dictionaries
# variable of type string
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
name = "David Vasilev"
print("name", name, type(name))
print()
# variable of type integer
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
age = 16
print("age", age, type(age))
print()
# variable of type float
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
score = 100.0
print("score", score, type(score))
print()
# variable of type list (many values in one variable)
print("What is variable name/key?", "value?", "type?", "primitive or collection?")
print("What is different about the list output?")
langs = ["Python", "JavaScript", "Java", "Bash"]
print("langs", langs, type(langs), "length", len(langs))
print("- langs[0]", langs[0], type(langs[0])) #change the number values to change the output from the list
print()
# variable of type dictionary (a group of keys and values)
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
print("What is different about the dictionary output?")
person = {
"name": name,
"age": age,
"score": score,
"langs": langs
} #creates a list
print("person", person, type(person), "length", len(person)) #prints the whole list
print('- person["name"]', person["name"], type(person["name"])) #prints one item from the list
InfoDb = []
# InfoDB is a data structure with expected Keys and Values
# My Dictionary
InfoDb.append({
"FirstName": "David",
"LastName": "Vasilev",
"DOB": "May 27",
"Residence": "San Diego",
"Email": "davidv42185@stu.powayusd.com",
"Owns_Cars": ["McLaren 720s, Ferrari 488"]
})
# Partner Dictionary
InfoDb.append({
"FirstName": "Akshat",
"LastName": "Parikh",
"DOB": "December 28",
"Residence": "San Diego",
"Email": "akshat1228@gmail.com",
"Owns_Cars": ["Rolls Royce Culinan, Mercedes Maybach, Mercedes G-Wagon, Ashton Martin Vantage"]
})
# Random Person Dictionary
InfoDb.append({
"FirstName": "Bob",
"LastName": "Smith",
"DOB": "January 1",
"Residence": "New York",
"Email": "bobsmith@gmail.com",
"Owns_Cars": ["Toyota", "Ford"]
})
# Print the data structure
print(InfoDb)
Formatting List/Dictionary (With For Loop)
- To start formatting the data,
print_data()
must be used. -
d_rec
must then be used to state that a dictionary record is going to be printed. - Use square brackets [] to place the terms that are going to be printed.
- Use
for_loop()
to loop theInfoDb
dictionary that was defined earlier until there are no more terms to print. -
print_data(record)
is used to pass the dictionary record to the function.
# print function: given a dictionary of InfoDb content
def print_data(d_rec):
print(d_rec["FirstName"], d_rec["LastName"]) # using comma puts space between values
print("\t", "Residence:", d_rec["Residence"]) # \t is a tab indent
print("\t", "Birth Day:", d_rec["DOB"])
print("\t", "Email:", d_rec["Email"])
print("\t", "Cars: ", end="") # end="" make sure no return occurs
print(", ".join(d_rec["Owns_Cars"])) # join allows printing a string list with separator
print()
# for loop algorithm iterates on length of InfoDb
def for_loop():
print("For loop output\n")
for record in InfoDb:
print_data(record)
for_loop()
# while loop algorithm contains an initial n and an index incrementing statement (n += 1)
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()
# recursion algorithm loops 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)
Hacks Questions
- Would it be possible to output data in a reverse order?
Yes, a loop and reversed()
can be used to reverse the order of the printed dictionary.
- Are there other methods that can be performed on lists?
Lists can be used to create quizzes and listing items, such as shopping lists and data about a certain entity.
- Could you create new or add to dictionary data set? Could you do it with input?
You can add to a dictionary data set by creating and defining a new list. You could ask the user for an input and then store their input as a list, which can later be outputted when called upon.
import getpass, sys # importing libraries for quiz
def question_and_answer(prompt):
print("Question:" + prompt)
msg = input("Question:" +prompt)
print("Answer:" + msg)
def question_with_response(prompt):
print("Question: " + prompt)
msg = input("Question: " + prompt)
return msg
q_list = []
q_list.append({
"Question": "What command is used to include other functions that were previously developed?",
"Answer": "import",
})
q_list.append({
"Question": "What command is used to evaluate correct or incorrect response in this example?",
"Answer": "if",
})
q_list.append({
"Question": "Each 'if' command contains an '_________' to determine a true or false condition?",
"Answer": "expression",
})
q_list.append({
"Question": "What are words surrounded by quotation marks called?",
"Answer": "strings",
})
q_list.append({
"Question": "What tab in Github is used to monitor the status of the changes you push?",
"Answer": "actions",
})
questions = len(q_list) #total number of questions asked
correct = 0 #default number of questions correct
print('Hello, ' + getpass.getuser() + " running " + sys.executable) #prints the greeting of the test
print("You will be asked " + str(questions) + " questions.") #prints the amount of questions that are going to be asked
rsp = question_with_response("Are you ready to take a test?") #asks for user input before starting the test
if rsp == "yes": #compares the user's input to the correct answer, which is "import"
print("Lets Start!")
for question in q_list:
print(question["Question"])
response = input(question["Question"])
if response == question["Answer"]:
print(response + " is the correct answer!")
correct = correct + 1
else:
print(response + " is incorrect.")
quotient = correct / questions #defines quotient
ptge = quotient * 100 #defines ptge
print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions) + " or " + str(ptge) + "%") #this prints the score that the user gets