Python Week 2
Learning about lists and dictionaries.
- Running the Code
- Using Append
- For Loops
- For Loop with an Index
- Using the While Loop and Inputs
- Recursion
- Tools
- Reverse Order
- Sort and Set
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
name = "John Doe"
print("name", name, type(name))
print()
# variable of type integer
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
age = 18
print("age", age, type(age))
print()
# variable of type float
print("What is the variable name/key?", "value?", "type?", "primitive or collection, why?")
score = 90.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"]
print("langs", langs, type(langs), "length", len(langs))
print("- langs[0]", langs[0], type(langs[0]))
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
}
print("person", person, type(person), "length", len(person))
print('- person["name"]', person["name"], type(person["name"]))
print(langs[1]) # Will output "Java"
print
InfoDb = []
# InfoDB is a data structure with expected Keys and Values
# Append to List a Dictionary of key/values related to a person and cars
InfoDb.append({
"FirstName": "John",
"LastName": "Mortensen",
"DOB": "October 21",
"Residence": "San Diego",
"Email": "jmortensen@powayusd.com",
"Owns_Cars": ["2015-Fusion", "2011-Ranger", "2003-Excursion", "1997-F350", "1969-Cadillac"]
})
# Append to List a 2nd Dictionary of key/values
InfoDb.append({
"FirstName": "Sunny",
"LastName": "Naidu",
"DOB": "August 2",
"Residence": "Temecula",
"Email": "snaidu@powayusd.com",
"Owns_Cars": ["4Runner"]
})
# My information
InfoDb.append({
"FirstName": "Arnav",
"LastName": "Kanekar",
"DOB": "July 3",
"Residence": "San Diego",
"Email": "**********@*****.***", # Censored
"Owns_Cars": "None"
})
# Using input to add information to the dictionary
InfoDb.append({
"FirstName": input("What is your first name?"),
"LastName": input("What is your last name?"),
"DOB": input("What is your date of birth(Month, day)?"),
"Residence": input("Where do you live?"),
"Email": input("What is your email?"),
"Owns_Cars": input("What cars do you own?")
})
# Print the data structure
print(InfoDb)
sports = ["football", "track", "soccer", "basketball", "tennis"] # list
# iterates based on the range, so in this case it will only iterate 5 times
for i in range(5):
print(sports[i]) # would not print more than 5 sports, even if list is longer
cake_flavors = ["chocolate", "strawberry", "vanilla"] # List
# For loop, for index in list
for i in cake_flavors:
print(i) # Print the flavor
meals = {} # empty dictionary
length = 4
# runs as long as there are less than 4 items in the dictionary
while len(meals) < length:
name = input("Name a food.")
rating = input("How would you rate the meal on a scale of 1 - 10?")
meals[name] = rating # determines the key and the value
print(meals)
def factorial(i): # defining the function
if i == 0: # will not recall function
return 1
if i == 1: # will not recall function
return i
if i != 1:
return i * factorial(i - 1) # recalls the function, but at lesser value
print(factorial(5))
print(factorial(0))
print(factorial(1))
countdown = [3, 2, 1] # New list
print(countdown)
countdown.reverse() # Reversing the list
print(countdown)
This shows that the .reverse()
statement is used to reverse a list.
cake_flavors = ["chocolate", "strawberry", "vanilla"]
# Appending multiple items
cake_flavors.append("red velvet")
cake_flavors.append("lemon")
cake_flavors.append("marble")
print(cake_flavors) # Printing the new list
# Sort function
cake_flavors.sort()
print(cake_flavors) # Alphabetized list
# Appending more flavors
cake_flavors.append("lemon")
cake_flavors.append("german chocolate")
cake_flavors.append("carrot")
print(cake_flavors)
cake_flavors = set(cake_flavors)
print(cake_flavors)
Showcases the .append()
, .sort()
, and set()
. Append adds a new item to the list, sort puts the list in alphabetical order, and set removes any duplicatte items.
quiz = [] # empty list
#variables
question_count = 5
score = 0
# appending some questions
quiz.append({
"What type of language is Python" : "object oriented",
"How do you get an output in Python?" : "print"
})
quiz.append({
"Is a dictionary a primitive or a collection?" : "collection",
"How do you add more information to a list?" : "append",
"What do you need to call to get the value in a dictionary?" : "key"
})
# function to print questions and get answers
def questioning(ask):
print("Question: " + ask)
global ans
ans = input()
print("Answer: " + ans)
# for loop to iterate through the dictionary
for dict in quiz:
for question, answer in dict.items(): # for the key and value pair
questioning(question) # calling function
if ans.lower() == answer:
score += 1
print("Your answer is correct.")
else:
print("You are incorrect.")
# percentage calculator from last time
def grade(sco, quests):
percent = 100 * float(sco)/float(quests)
return percent
quiz_percentage = grade(score, question_count) # Defining variable
print("You got " + str(score) + " of " + str(question_count) + " questions correct.")
print("Your score is " + str(quiz_percentage) + "%.")