Hi!

On this page I will demonstrate loops... again like I did on my python quiz. But first we have to make a dictionary within a list. This will store a lot of information.. Most of the variable names are self-explanatory... DOB stands for Date of Birth

InfoDb = []


# Append my info
InfoDb.append({
    "FirstName": "Leonard",
    "LastName": "Wright",
    "DOB": "December 13",
    "Highest School": "Del Norte High School",
    "Favorite Course": "AP Comp Sci Principles",
    "Occupation": "Student",
    "Favorite Food": "Panko Chicken",
    "Favorite Color": "Brown",
    "Favorite Movie": "Back to the Future",
    "Favorite Activity": "Experimenting with Computers",
})

# Append my sister's info
InfoDb.append({
    "FirstName": "Lindsay",
    "LastName": "Wright",
    "DOB": "December 3",
    "Highest School": "Rice University",
    "Favorite Course": "Fluid Mechanics",
    "Occupation": "Student, Research Intern, Systems Engineer",
    "Favorite Food": "Wonton",
    "Favorite Color": "Green",
    "Favorite Movie": "The Martian",
    "Favorite Activity": "Hiking",
})

# Appends my mother's info
InfoDb.append({
    "FirstName": "Marilyn",
    "LastName": "Wright",
    "DOB": "June 12",
    "Highest School": "San Beda Law School",
    "Favorite Course": "Constitutional Law",
    "Occupation": "Lawyer, Mother",
    "Favorite Food": "Rice",
    "Favorite Color": "Green",
    "Favorite Movie": "",
    "Favorite Activity": "",
})

# Appends my father's info
InfoDb.append({
    "FirstName": "Leonard",
    "LastName": "Wright",
    "DOB": "June 24",
    "Highest School": "Cal State Fullerton",
    "Favorite Course": "Marketing",
    "Occupation": "CPA, Father",
    "Favorite Food": "Salmon",
    "Favorite Color": "Blue",
    "Favorite Movie": "Gone with the Wind",
    "Favorite Activity": "",
})

# Appends a friend's info
InfoDb.append({
    "FirstName": "Kevin",
    "LastName": "Vu",
    "DOB": "November 2",
    "Highest School": "Del Norte High School",
    "Favorite Course": "",
    "Occupation": "student, ",
    "Favorite Food": "",
    "Favorite Color": "",
    "Favorite Movie": "",
    "Favorite Activity": "",
})

# Appends info of John Smith, a fictitious individual
InfoDb.append({
    "FirstName": "John",
    "LastName": "Smith",
    "DOB": "February 29",
    "Highest School": "UC San Diego",
    "Favorite Course": "Differential Calculus",
    "Occupation": "Professor",
    "Favorite Food": "Beef Stew",
    "Favorite Color": "Red",
    "Favorite Movie": "Star Wars: The Empire Strikes Back",
    "Favorite Activity": "Swimming",
})

# We're not using the print command anymore because what it spits out is a mess.

Defining a function

Now that I have everything compiled into a nice dictionary, it's time to demonstrate the power of the loops. But before I do that, I'll define a function to make life easier. I'll name it print_data. That way, I can call print_data instead of having to re-type all of those print commands.

# This special d_rec parameter essentially references the dictionary we just created.
def print_data(d_rec):
    print(d_rec["FirstName"], d_rec["LastName"])
#these \t print indents, which are usually inserted with a tab.
    print("\t", "Birth Day:", d_rec["DOB"])
    print("\t", "Highest School:", d_rec["Highest School"])
    print("\t", "Occupation:", d_rec["Occupation"])
    print("\t", "Favorite Course:", d_rec["Favorite Course"])
    print("\t", "Favorite Food:", d_rec["Favorite Food"])
    print("\t", "Favorite Color:", d_rec["Favorite Color"])
    print("\t", "Favorite Movie:", d_rec["Favorite Movie"])
    print("\t", "Favorite Activity:", d_rec["Favorite Activity"])
    print()
    print()

The For Loop

Now that the function is defined, I can demonstrate the first loop: the for loop.

# It will execute this set of commands for each individual
# who's information is stored in InfoDb
# InfoDb is a dictionary in a list.
def for_loop():
    print("For loop output\n")
    for record in InfoDb: #index variable is "record"
        print_data(record)

for_loop()
For loop output

Leonard Wright
	 Birth Day: December 13
	 Highest School: Del Norte High School
	 Occupation: Student
	 Favorite Course: AP Comp Sci Principles
	 Favorite Food: Panko Chicken
	 Favorite Color: Brown
	 Favorite Movie: Back to the Future
	 Favorite Activity: Experimenting with Computers


Lindsay Wright
	 Birth Day: December 3
	 Highest School: Rice University
	 Occupation: Student, Research Intern, Systems Engineer
	 Favorite Course: Fluid Mechanics
	 Favorite Food: Wonton
	 Favorite Color: Green
	 Favorite Movie: The Martian
	 Favorite Activity: Hiking


Marilyn Wright
	 Birth Day: June 12
	 Highest School: San Beda Law School
	 Occupation: Lawyer, Mother
	 Favorite Course: Constitutional Law
	 Favorite Food: Rice
	 Favorite Color: Green
	 Favorite Movie: 
	 Favorite Activity: 


Leonard Wright
	 Birth Day: June 24
	 Highest School: Cal State Fullerton
	 Occupation: CPA, Father
	 Favorite Course: Marketing
	 Favorite Food: Salmon
	 Favorite Color: Blue
	 Favorite Movie: Gone with the Wind
	 Favorite Activity: 


Kevin Vu
	 Birth Day: November 2
	 Highest School: Del Norte High School
	 Occupation: student, 
	 Favorite Course: 
	 Favorite Food: 
	 Favorite Color: 
	 Favorite Movie: 
	 Favorite Activity: 


John Smith
	 Birth Day: February 29
	 Highest School: UC San Diego
	 Occupation: Professor
	 Favorite Course: Differential Calculus
	 Favorite Food: Beef Stew
	 Favorite Color: Red
	 Favorite Movie: Star Wars: The Empire Strikes Back
	 Favorite Activity: Swimming


I first define the for_loop function. It prints the string in parenthesis to the terminal. Then:

for record in InfoDb:

for has a function: it cycles through all items in a list, and for each cycle the commands associated with the loop are executed. Keep in mind that InfoDb is a list of dictionary entires, and the items in this list are each person (ex: Leonard Wright, Lindsay Wright), etc.

record serves as an index variable. Index variables can be named anything, but have a very specialized function. They work with a loop (whether this be a for loop, a while loop, or a recursive loop) to iterate through each item in a list. There is a nuance to index variables: they assign a value to each item in a list, but it starts counting from 0 rather than 1 (since 0 is the number with the least value). So the first entry in the list will be associated with 0, etc. This nuance will be important in explaining the while loop.

print_data(record) then prints the information of each user. Keep in mind the index variable record.

If you really want another example and explanation of a for loop, you should check out my first python quiz script.

The While Loop + Backwards output

You already saw the output of my for loop. I will now demonstrate a while loop while reversing the output of the list.

def while_loop():
    print("While loop output\n")
    i = len(InfoDb) - 1 #Starts on last entry
    while i > -1: #Ensures the first entry (where i = 0) is printed
        record = InfoDb[i]
        print_data(record)
        i -= 1 #Goes to previous entry (rather than next entry)
    return

while_loop()
While loop output

John Smith
	 Birth Day: February 29
	 Highest School: UC San Diego
	 Occupation: Professor
	 Favorite Course: Differential Calculus
	 Favorite Food: Beef Stew
	 Favorite Color: Red
	 Favorite Movie: Star Wars: The Empire Strikes Back
	 Favorite Activity: Swimming


Kevin Vu
	 Birth Day: November 2
	 Highest School: Del Norte High School
	 Occupation: student, 
	 Favorite Course: 
	 Favorite Food: 
	 Favorite Color: 
	 Favorite Movie: 
	 Favorite Activity: 


Leonard Wright
	 Birth Day: June 24
	 Highest School: Cal State Fullerton
	 Occupation: CPA, Father
	 Favorite Course: Marketing
	 Favorite Food: Salmon
	 Favorite Color: Blue
	 Favorite Movie: Gone with the Wind
	 Favorite Activity: 


Marilyn Wright
	 Birth Day: June 12
	 Highest School: San Beda Law School
	 Occupation: Lawyer, Mother
	 Favorite Course: Constitutional Law
	 Favorite Food: Rice
	 Favorite Color: Green
	 Favorite Movie: 
	 Favorite Activity: 


Lindsay Wright
	 Birth Day: December 3
	 Highest School: Rice University
	 Occupation: Student, Research Intern, Systems Engineer
	 Favorite Course: Fluid Mechanics
	 Favorite Food: Wonton
	 Favorite Color: Green
	 Favorite Movie: The Martian
	 Favorite Activity: Hiking


Leonard Wright
	 Birth Day: December 13
	 Highest School: Del Norte High School
	 Occupation: Student
	 Favorite Course: AP Comp Sci Principles
	 Favorite Food: Panko Chicken
	 Favorite Color: Brown
	 Favorite Movie: Back to the Future
	 Favorite Activity: Experimenting with Computers


So we first define a function and print how there's output...

Then you notice that i is defined. The len(list_name) command will become the number of entries in the list named list_name. Now, let me paste the actual line.

i = len(InfoDb) - 1

Noticed how I subtracted 1 from the len(InfoDb)? Well that's because the final entry in the list will have a value one less than the number of entries in the list, since the first entry is assigned a 0 instead of a 1. You will see that the next line of code takes this into account as well. This also means that we will print the final entry of the list first.

while i > -1:

The while command will execute all associated commands as long as a statement is true. When iterating through lists, this typically involves setting the index variable (in this case, i) equal to a value, then adding a value until it reaches a value such that all entries in a list have been cycled through the commands. The condition is typically that i is less than or greater than a certain value. Now notice that my condition is that i is greater than negative one. This is because I want my first entry of the list, where i is set to 0, to print. Then,

record = InfoDb[i]
     print_data(record)
     i -= 1

This makes a record variable, which is equal to entry i (whatever value i is for that execution cycle is). It then executes the print_data function on that entry of the list of dictionaries. Finally, the value of i decreases by 1. This ensures that the entry in the list before the previously printed entry is printed next. This essentially makes it so the entries are printed backwards.

Recursive Loops

Recursive loops are quite similar to while loops in terms of structure. What is interesting about them is that a function is defined, and the list of commands within the function includes the function.

Now, I will also try to do something fun. I will try to randomize the order which the entries in the list are printed. The nature of the command which randomizes entry order overrides the list the command is performed on. I wish to preserve the original list, so I'll make a copy of the original list.

import random

# makes copy of InfoDb list
InfoDb_random = InfoDb

# randomizes order of entries in InfoDb_random
random.shuffle(InfoDb_random)

#The actual recursive loop starts here
def recursive_loop(i):
    if i < len(InfoDb_random):
        record = InfoDb_random[i]
        print_data(record)
        recursive_loop(i + 1)
    return

print("Recursive loop output\n")
recursive_loop(0)
Recursive loop output

Lindsay Wright
	 Birth Day: December 3
	 Highest School: Rice University
	 Occupation: Student, Research Intern, Systems Engineer
	 Favorite Course: Fluid Mechanics
	 Favorite Food: Wonton
	 Favorite Color: Green
	 Favorite Movie: The Martian
	 Favorite Activity: Hiking


Leonard Wright
	 Birth Day: December 13
	 Highest School: Del Norte High School
	 Occupation: Student
	 Favorite Course: AP Comp Sci Principles
	 Favorite Food: Panko Chicken
	 Favorite Color: Brown
	 Favorite Movie: Back to the Future
	 Favorite Activity: Experimenting with Computers


John Smith
	 Birth Day: February 29
	 Highest School: UC San Diego
	 Occupation: Professor
	 Favorite Course: Differential Calculus
	 Favorite Food: Beef Stew
	 Favorite Color: Red
	 Favorite Movie: Star Wars: The Empire Strikes Back
	 Favorite Activity: Swimming


Kevin Vu
	 Birth Day: November 2
	 Highest School: Del Norte High School
	 Occupation: student, 
	 Favorite Course: 
	 Favorite Food: 
	 Favorite Color: 
	 Favorite Movie: 
	 Favorite Activity: 


Marilyn Wright
	 Birth Day: June 12
	 Highest School: San Beda Law School
	 Occupation: Lawyer, Mother
	 Favorite Course: Constitutional Law
	 Favorite Food: Rice
	 Favorite Color: Green
	 Favorite Movie: 
	 Favorite Activity: 


Leonard Wright
	 Birth Day: June 24
	 Highest School: Cal State Fullerton
	 Occupation: CPA, Father
	 Favorite Course: Marketing
	 Favorite Food: Salmon
	 Favorite Color: Blue
	 Favorite Movie: Gone with the Wind
	 Favorite Activity: 


I hope the comments were enough to explain everything but the recursive loop.

def recursive_loop(i):
    if i < len(InfoDb_random):
        record = InfoDb_random[i]
        print_data(record)
        recursive_loop(i + 1)
    return

print("Recursive loop output\n")
recursive_loop(0)
  1. In the first line, we define our recursive_loop. Notice that the parameter is the index variable, i
  2. In the second line, we give an if statement. The condition is that i is less than the number of entries in the list InfoDb_random, or that not all entries in the list have been cycled through the loop. This should show you that we are cycling the entries in order of first, second, third... then last. Also remember that the order of entries of InfoDb_random are a randomized version of that of InfoDb.
  3. Makes a record variable, which is set equal to the entry in the InfoDb_random list which is associated with the value of i
  4. Executes the print_data function with record (or an entry in the list InfoDb_random) as the parameter
  5. The function calls itself, essentially looping back to the top of the list of associated commands, but adding 1 to the index variable.
  6. return stores all the output in the main script so that it can be used outside of the function

Then notice the recursive_loop(0). It tells the script to start with i=0, or essentially the first entry in InfoDb_random

Making a Quiz using a List of Dictionaries!

You probably saw my first python quiz. All the questions were collected onto a single list, which ultimately made that list a very long line. That's messy and disorganized. Let's use a list of dictionaries to make it more organized. But first, let's define the list, or the questions and answers... and the function, question_with_response.

import time, random

#Makes a new list for our quiz
QuizDB = []

#Appends all the quiz questions into our list.
#This quiz will be a relatively simple geography quiz.
#Notice that I use the database_name.append.

QuizDB.append({
    "Country": "Uruguay",
    "Continent": "South America",
})

QuizDB.append({
    "Country": "Austria",
    "Continent": "Europe",
})

QuizDB.append({
    "Country": "United Arab Emirates",
    "Continent": "Asia",
})

QuizDB.append({
    "Country": "Sweden",
    "Continent": "Europe",
})

QuizDB.append({
    "Country": "Tanzania",
    "Continent": "Africa",
})

QuizDB.append({
    "Country": "Yemen",
    "Continent": "Asia",
})

QuizDB.append({
    "Country": "Mauritania",
    "Continent": "Africa",
})

QuizDB.append({
    "Country": "Peru",
    "Continent": "South America",
})

QuizDB.append({
    "Country": "South Korea",
    "Continent": "Asia",
})

QuizDB.append({
    "Country": "Singapore",
    "Continent": "Asia",
})

#Define question_with_response to give question prompts and collect input
#As a reminder, print() prints the parameter (in parenthesis) into terminal
def question_with_response(prompt): 
    print("Question: What continent is " + prompt + " in?")
    msg = input()
    return msg

Then I'll make the quiz.

random.shuffle(QuizDB)

#Define variables
questions = 10
correct = 0

#I'll take some personal liberties with the initial prompt
print("Hi! Welcome to my Python Geography quiz! Please capitalize the names of continents.")
print("You got 15 nanoseconds to prepare for this quiz. Say yes!")

#Disables input and output for 15 seconds.
time.sleep(15)

#Cycles through the quiz questions
for i in QuizDB:
    rsp = question_with_response(i["Country"])
    if rsp == i["Continent"]:
        print(rsp + " is correct!")
        correct += 1
    else:
        print(rsp + " is incorrect! The answer was", i["Continent"])
        
#Calculates percent correct answers.
percent = (correct/questions) * 100 
    
#Prints accuracy of answers to terminal
print("You scored " + str(percent) + '%!')
Hi! Welcome to my Python Geography quiz! Please capitalize the names of continents.
You got 15 nanoseconds to prepare for this quiz. Say yes!
Question: What continent is Singapore in?
Asia
Asia is correct!
Question: What continent is Sweden in?
Europe
Europe is correct!
Question: What continent is Yemen in?
Asia
Asia is correct!
Question: What continent is South Korea in?
Asia
Asia is correct!
Question: What continent is Uruguay in?
South America
South America is correct!
Question: What continent is Mauritania in?
Africa
Africa is correct!
Question: What continent is United Arab Emirates in?
Asia
Asia is correct!
Question: What continent is Austria in?
Europe
Europe is correct!
Question: What continent is Peru in?
South America
South America is correct!
Question: What continent is Tanzania in?

I think the code that needs the most explaining here is the for loop. I'll bring it down here.

for i in QuizDB:
    rsp = question_with_response(i["Country"])
    if rsp == i["Continent"]:
        print(rsp + " is correct!")
        correct += 1
    else:
        print(rsp + " is incorrect! The answer was", i["Continent"])
  1. Line 1: For each entry in the list of dictionaries QuizDB, the associated commands will be executed
  2. Make a rsp variable. It is set equal to the input garnered from the question_with_response function. Notice the parameter of question_with_response is i["country"]. i is the index variable. For the current associated item in the list, the string associated with "Country" will be used as the parameter to question_with_response
  3. An if statement with the condition that the input collected is equal to the string associated with "Continent" for that list. The string associated with "Continent" in this case is the correct answer, or the continent that the associated country is in.
  4. If the condition is satisfied, then the fact that the answer was correct is outputted to the terminal and
  5. The variable correct (which is the number of questions answered correctly) is increased by one
  6. An else statement (if the if condition is not satisfied, associated commands are executed)
  7. prints to the terminal that the question was answered incorrectly, and also shows the correct answer.

Append to a list with user input

There is one more thing I want to do for hacks, and that is appending to a list with user input. From my experience, collecting variables will be very helpful. I will be appending to the QuizDB list to make things simpler. Let me demonstrate below:

def append_input():
    print("Do you want to add a new country/continent question? [y/n]")
    yesno = input()
#Starts appending sequence
    if yesno == "y":
        print()
        print ("What country do you want to append?")
        country_app = input()
        print()
        print("What continent do you want to append?")
        continent_app = input()
        QuizDB.append({
            "Country": f"{country_app}",
            "Continent": f"{continent_app}",
        })
        print()
        append_input()
#exits function if n is given
    elif yesno == "n":
        return
#Prevents issues if initial input was something other than y or n.
#Re-executes the first command
    else: append_input()
        
append_input()
Do you want to add a new country/continent question? [y/n]
a
Do you want to add a new country/continent question? [y/n]
s
Do you want to add a new country/continent question? [y/n]
y

What country do you want to append?
United States

What continent do you want to append?
North America

Do you want to add a new country/continent question? [y/n]
y

What country do you want to append?
Japan

What continent do you want to append?
Asia

Do you want to add a new country/continent question? [y/n]
y

What country do you want to append?
Ukraine

What continent do you want to append?
Europe

Do you want to add a new country/continent question? [y/n]
y

What country do you want to append?
Mexico

What continent do you want to append?
Europe

Do you want to add a new country/continent question? [y/n]
y

What country do you want to append?
Atlantis

What continent do you want to append?
Atlantic Ocean

Do you want to add a new country/continent question? [y/n]
y

What country do you want to append?
Tennessee

What continent do you want to append?
United States

Do you want to add a new country/continent question? [y/n]
n

Notice that you can input anything into the list, including fictitious places or incorrect information. This python code does not know fact from fiction. It will just store whatever you give it. That's how it works.

Now, I didn't put comments on the part where the if statement is satisfied. I did that since that would lead to a bit of confusion with what the associated command are, etc. I'll paste the commands associated with the if condition right here

if yesno == "y":
        print()
        print ("What country do you want to append?")
        country_app = input()
        print()
        print("What continent do you want to append?")
        continent_app = input()
        QuizDB.append({
            "Country": f"{country_app}",
            "Continent": f"{continent_app}",
        })
        print()
        append_input()
  • Line 1 is the if statement itself. If a user wants to append questions, he/she would have given a y response.
  • The question of which country to input is then given in the terminal.
  • Line 4 collects this input and stores it as country_app. app is the first three letters of "append."
  • The notice to input the continent is printed into the terminal. This input is collected as continent_app
  • The inputted information is appended into QuizDB.
  • Notice how Country is associated with f"{country_app}". The f, or format command is essentially used to bypass all of those issues with quotation marks. This and the curly brackets allows the value of the input (instead of country_app as a string) to be stored into the dictionary. A similar process is used for continents.
  • Finally, the function append_input() calls itself again to give the user a chance to input another country/continent set.

Now, to test to see that the information is actually appended, we will take the quiz... again! And see me "mess up" on all the questions I intentionally misconfigured.

random.shuffle(QuizDB)

#Define variables
questions = 0
correct = 0

#Cycles through the quiz questions
for i in QuizDB:
    questions += 1
    rsp = question_with_response(i["Country"])
    if rsp == i["Continent"]:
        print(rsp + " is correct!")
        correct += 1
    else:
        print(rsp + " is incorrect! The answer was", i["Continent"])
        
#Calculates percent correct answers.
percent = (correct/questions) * 100 
    
#Prints accuracy of answers to terminal
print("You scored " + str(percent) + '%!') 
Question: What continent is Tennessee in?
North America
North America is incorrect! The answer was United States
Question: What continent is United States in?
North America
North America is correct!
Question: What continent is Peru in?
South America
South America is correct!
Question: What continent is South Korea in?
Asia
Asia is correct!
Question: What continent is Mexico in?
North America
North America is incorrect! The answer was Europe
Question: What continent is Yemen in?
Asia
Asia is correct!
Question: What continent is Atlantis in?
what
what is incorrect! The answer was Atlantic Ocean
Question: What continent is Singapore in?
Asia
Asia is correct!
Question: What continent is Japan in?
Asia
Asia is correct!
Question: What continent is Tanzania in?
Africa
Africa is correct!
Question: What continent is United Arab Emirates in?
Asia
Asia is correct!
Question: What continent is Sweden in?
Europe
Europe is correct!
Question: What continent is Mauritania in?
Africa
Africa is correct!
Question: What continent is Ukraine in?
Europe
Europe is correct!
Question: What continent is Austria in?
Europe
Europe is correct!
Question: What continent is Uruguay in?
South America
South America is correct!
You scored 81.25%!

There was one notable change I made. I initially set the questions variable to 0, and automated the increase of the question variable. See the for loop:

for i in QuizDB:
    questions += 1
    rsp = question_with_response(i["Country"])
    if rsp == i["Continent"]:
        print(rsp + " is correct!")
        correct += 1
    else:
        print(rsp + " is incorrect! The answer was", i["Continent"])

Notice that the first command associated with the for loop is increasing the value of questions by 1. That way, the number of questions is automated and I don't have to count to make a pre-set value.