- Mana Vale
Fourth Class Recap
Updated: Oct 19, 2020
Here is the PowerPoint with the material we covered in our latest class:
Topics Covered:
Lists, continued
Dictionaries
Secret code program (encryption)
Lists, continued:
Looping through a List - While Loop:
Unlike a for-loop, in a while loop, you must explicitly provide the index of the item you would like to retrieve from your list
You would need to keep track of the index and keep increasing it by one with every iteration (repetition) of the loop
Let's look at an example:
fruits = ["apple", "banana", "orange", "kiwi", "blueberries"]
index = 0
while (index < 5):
print(fruits[index])
index += 1
This should yield:
>>>
apple
banana
orange
kiwi
blueberries
Adding Elements to a List:
There are multiple ways to add new elements/items to a list
One way is to use the .append(element) function
Another way is to use the .insert(index, element) function
Using Append:
team = ["Rachael", "Mana"]
team.append("Minseo")
print(team)
>>>
['Rachael', 'Mana', 'Minseo']
Using Insert:
team = ["Rachael", "Mana"]
team.insert(1, "Minseo")
print(team)
>>>
['Rachael', 'Minseo', 'Mana']
Dictionaries:
In the dictionaries we use, we look up a word and find its definition
It's the same idea with Python dictionaries -- each entry is called a "key-value pair", which are equivalent to word-definition pairs in our dictionaries
Each key corresponds to some value, and each key-value pair is separated by commas
We can define (create) a dictionary using curly braces: { }
Here's an example of a dictionary that defines multiple properties of an object:
apple = {
"color" : "red",
"shape" : "round",
"seeds" : True
}
There are two different ways of retrieving a value from a dictionary:
#using ["key"]
print(apple["color"])
#using .get(key)
print(apple.get("color"))
Both will return "red".
Adding Entries to a Dictionary:
You can add more items to your dictionary by defining a value for a new key
apple["on a tree"] = True
print(apple)
>>>
{'color' : 'red', 'shape' : 'round', 'seeds' : True, 'on a tree' : True}
Print all the keys, values, and key-value pairs:
#print keys
students = { "Rachael" : 12, "Mana" : 11, "Minseo" : 10}
for student in students:
print(student)
>>>
Mana
Rachael
Minseo
Note: a dictionary is unordered, so its elements are not printed based on their positions
If you wanted to print the keys in alphabetical order, you could do this:
print(sorted(students.keys()))
students.keys() is a function that converts the keys of a dictionary into a list. This list maintains the same order as the printed keys, so in order to put the elements in alphabetical order, we use the built-in sorted() function. You can learn more about it here.
#print values
for key in students:
print(students[key])
>>>
11
12
10
#print keys and values
for item in students.items():
print(item)
>>>
('Mana', 11)
('Rachael', 12)
('Minseo', 10)
TRY1: Write a program that stores users' names and their usernames in a dictionary.
Ask the user for their name and username
Store the user inputs in a dictionary called 'users'
Use name as a key and username as a value
Print out all the keys and values of the dictionary in alphabetical order (based on the key)
Your program should output something like this when it's run:
>>>
('Mana', 11)
('Minseo', 10)
('Rachael', 12)
Secret Code Program Description:
We will create a function that takes in a word or message and returns an encoded sequence of numbers
Each number represents a character (based on the system A = 1, B = 2, C = 3 up to Z = 26)
We can add numbers to represent a space, comma, and period, too
We will use a dictionary to keep track of which letter corresponds to which number
cipher_key = {"A": 1,
"B": 2,
"C": 3,
"D": 4,
"E": 5,
"F": 6,
"G": 7,
"H": 8,
"I": 9,
"J": 10,
"K": 11,
"L": 12,
"M": 13,
"N": 14,
"O": 15,
"P": 16,
"Q": 17,
"R": 18,
"S": 19,
"T": 20,
"U": 21,
"V": 22,
"W": 23,
"X": 24,
"Y": 25,
"Z": 26,
" ": 27,
",": 28,
".": 29}
def encipher(string):
enciphered = '' #an empty string
for char in string: #for each character in the string
enciphered += str(cipher_key.get(char))
return enciphered
When the encipher function is called, a new string (enciphered) will be created, and the program will loop through the inputted string and add the corresponding number of each character to the new string.
Let's break down this line:
enciphered += str(cipher_key.get(char))
We learned earlier that += is just a shortened way of saying that we're adding whatever is on the right side of the symbol to whatever already exists on the left side. We also learned that str() is a function that can be used to give an integer the properties of a string and therefore the ability to be inputted into functions specific to strings. str() encloses the integer in quotes and essentially converts it to a string.
With the .get() function, we access the numerical value of the current character we have landed on in our loop and retrieve it. We feed this into the str() function, and this value gets added to the enciphered string.
That's it! Pretty cool, huh? Now you can write secret messages! Remember: if you try to encode a secret message that has lowercase letters in it, Python will give you an error because your dictionary only contains uppercase letters.
print(encipher("HELLO."))
>>>
8512121529
There is a way to write a decipher function such that it takes in a number and returns the corresponding string. However, it is a little complex and requires more explanation. If you are interested in learning how to code this function, shoot me an email and I'd be happy to explain!