Types of Variables in Python

# 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
What is the variable name/key? value? type? primitive or collection, why?
name David Vasilev <class 'str'>

What is the variable name/key? value? type? primitive or collection, why?
age 16 <class 'int'>

What is the variable name/key? value? type? primitive or collection, why?
score 100.0 <class 'float'>

What is variable name/key? value? type? primitive or collection?
What is different about the list output?
langs ['Python', 'JavaScript', 'Java', 'Bash'] <class 'list'> length 4
- langs[0] Python <class 'str'>

What is the variable name/key? value? type? primitive or collection, why?
What is different about the dictionary output?
person {'name': 'David Vasilev', 'age': 16, 'score': 100.0, 'langs': ['Python', 'JavaScript', 'Java', 'Bash']} <class 'dict'> length 4
- person["name"] David Vasilev <class 'str'>

Lists and Dictionaries

  • To list data use '.append(expression)'.
  • Dictionaries define words and then list the corresponding string.
  • This is a lost of things that are defined by one variable.
  • In this list there are words that are terms and each term is defined.
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)
[{'FirstName': 'David', 'LastName': 'Vasilev', 'DOB': 'May 27', 'Residence': 'San Diego', 'Email': 'davidv42185@stu.powayusd.com', 'Owns_Cars': ['McLaren 720s, Ferrari 488']}, {'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']}, {'FirstName': 'Bob', 'LastName': 'Smith', 'DOB': 'January 1', 'Residence': 'New York', 'Email': 'bobsmith@gmail.com', 'Owns_Cars': ['Toyota', 'Ford']}]

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 the InfoDb 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()
For loop output

David Vasilev
	 Residence: San Diego
	 Birth Day: May 27
	 Email: davidv42185@stu.powayusd.com
	 Cars: McLaren 720s, Ferrari 488

Akshat Parikh
	 Residence: San Diego
	 Birth Day: December 28
	 Email: akshat1228@gmail.com
	 Cars: Rolls Royce Culinan, Mercedes Maybach, Mercedes G-Wagon, Ashton Martin Vantage

Bob Smith
	 Residence: New York
	 Birth Day: January 1
	 Email: bobsmith@gmail.com
	 Cars: Toyota, Ford

Other Ways to Loop - while_loop

  • while_loop() can be used to to count through the number of terms in a dictionary and print it with while i < len(InfoDb): and then ending with print_data()
# 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()
While loop output

David Vasilev
	 Residence: San Diego
	 Birth Day: May 27
	 Email: davidv42185@stu.powayusd.com
	 Cars: McLaren 720s, Ferrari 488

Akshat Parikh
	 Residence: San Diego
	 Birth Day: December 28
	 Email: akshat1228@gmail.com
	 Cars: Rolls Royce Culinan, Mercedes Maybach, Mercedes G-Wagon, Ashton Martin Vantage

Bob Smith
	 Residence: New York
	 Birth Day: January 1
	 Email: bobsmith@gmail.com
	 Cars: Toyota, Ford

Repeating a Function - Recursion

  • recursive_loop(i) is used to activate the function with i=0
  • recursive_loop(i + 1) adds one to i, which moves through the function
  • when if i < len(InfoDb): the program ends because there is nothing left to print
# 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)
Recursive loop output

David Vasilev
	 Residence: San Diego
	 Birth Day: May 27
	 Email: davidv42185@stu.powayusd.com
	 Cars: McLaren 720s, Ferrari 488

Akshat Parikh
	 Residence: San Diego
	 Birth Day: December 28
	 Email: akshat1228@gmail.com
	 Cars: Rolls Royce Culinan, Mercedes Maybach, Mercedes G-Wagon, Ashton Martin Vantage

Bob Smith
	 Residence: New York
	 Birth Day: January 1
	 Email: bobsmith@gmail.com
	 Cars: Toyota, Ford

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.

Python Quiz Using Dictionaries

  • This is an example of a quiz that uses dictionaries to store the questions and answers.
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
Hello, davidv running /bin/python3
You will be asked 5 questions.
Question: Are you ready to take a test?
Lets Start!
What command is used to include other functions that were previously developed?
import is the correct answer!
What command is used to evaluate correct or incorrect response in this example?
if is the correct answer!
Each 'if' command contains an '_________' to determine a true or false condition?
expression is the correct answer!
What are words surrounded by quotation marks called?
strings is the correct answer!
What tab in Github is used to monitor the status of the changes you push?
actions is the correct answer!
davidv you scored 5/5 or 100.0%