Dictionary:
Add to a dictionary where the key is ‘x_position’ the value is 0 and the dictionary name is alien
Here is the cheatsheet source: http://ehmatthes.github.io/pcc/cheatsheets/README.html
alien[‘x_position’] = 0
Dictionary:
Looping through all key-value pairs in a dictionary called fav_numbers
fav_numbers = {‘eric’: 17, ‘ever’: 4}
for name, number in fav_numbers.items():
print(name + ‘ loves ‘ + str(number))
Dictionary:
1. fav_numbers = {'eric': 17, 'ever': 4}
for name in fav_numbers.keys():
print(name + ' loves a number')
2. fav_numbers = {'eric': 17, 'ever': 4}
for number in fav_numbers.values():
print(str(number) + ' is a favorite')Lists:
How do you check for a value in a list? E.g. check for ‘trek’ in a list called ‘bikes’
‘trek’ in bikes
List Comprehension:
Square all values in a range(1,11)
squares = [x**2 for x in range(1, 11)]
Functions:
Create a function with a default parameter
def make_pizza(topping='bacon'):
"""Make a single-topping pizza."""
print("Have a " + topping + " pizza!")
make_pizza()
make_pizza('pepperoni')Classes - Inheritance:
1. When you use inheritance, do you have to use super() to inherit the attributes in order to use the methods?
2.
class Rectangle:
def \_\_init\_\_(self, length, width):
self.length = length
self.width = width def area(self):
return self.length * self.width def perimeter(self):
return 2 * self.length + 2 * self.widthclass Square(Rectangle):
def \_\_init\_\_(self, length):
super().\_\_init\_\_(length, length)How to you read a text file and iterate through all lines in the file?
E.g. the text file name is ‘s.txt’
filename = 's.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line)
The ‘try’ statement should be followed by what other statement?
‘Except’. E.g.:
prompt = "How many tickets do you need? "
num_tickets = input(prompt)
try:
num_tickets = int(num_tickets)
except ValueError:
print("Please try again.")
else:
print("Your tickets are printing.")