lOMoAR cPSD| 6861666
Lists (cont.) Dictionaries
Beginner's Python List comprehensions
Dictionaries store connections between pieces of
information. Each item in a dictionary is a key-value pair.
Cheat Sheet squares = [x**2 for x in range(1, 11)]
Slicing a list
A simple dictionary
alien = {'color': 'green', 'points': 5}
finishers = ['sam', 'bob', 'ada', 'bea']
Accessing a value
Variables and Strings first_two = finishers[:2]
Variables are used to assign labels to values. A string is a print(f"The alien's color is
Copying a list {alien['color']}.")
series of characters, surrounded by single or double quotes.
Python's f-strings allow you to use variables inside strings to copy_of_bikes = bikes[:] Adding a new key-value pair
build dynamic messages.
alien['x_position'] = 0
Hello world
Tuples Looping through all key-value pairs
print("Hello world!") Tuples are similar to lists, but the items in a tuple can't be
modified. fav_numbers = {'eric': 7, 'ever': 4, 'erin':
Hello world with a variable 47}
msg = "Hello world!" Making a tuple
for name, number in fav_numbers.items():
print(msg) dimensions = (1920, 1080) print(f"{name} loves {number}.")
resolutions = ('720p', '1080p', '4K')
f-strings (using variables in strings) Looping through all keys
first_name = 'albert' fav_numbers = {'eric': 7, 'ever': 4, 'erin':
last_name = 'einstein' If statements 47}
full_name = f"{first_name} {last_name}" If statements are used to test for particular conditions and
print(full_name) for name in fav_numbers.keys():
respond appropriately.
print(f"{name} loves a number.")
Conditional tests Looping through all the values
fav_numbers = {'eric': 7, 'ever': 4, 'erin':
Lists 47}
A list stores a series of items in a particular order. You
access items using an index, or within a loop. for number in fav_numbers.values():
print(f"{number} is a favorite.")
, lOMoAR cPSD| 6861666
Make a list equal x == 42
not equal x != 42
bikes = ['trek', 'redline', 'giant']
greater than x > 42
User input
Your programs can prompt the user for input. All input is
or equal to x >= 42
Get the first item in a list stored as a string.
less than x < 42
first_bike = bikes[0] or equal to x <= 42 Prompting for a value
Conditional tests with lists
Get the last item in a list name = input("What's your name? ")
'trek' in bikes print(f"Hello, {name}!")
last_bike = bikes[-1]
'surly' not in bikes
Prompting for numerical input
Looping through a list
Assigning boolean values age = input("How old are you? ")
for bike in bikes: age = int(age)
game_active = True
print(bike)
can_edit = False
pi = input("What's the value of pi? ")
Adding items to a list pi = float(pi)
A simple if test
bikes = []
if age >= 18:
bikes.append('trek')
print("You can vote!")
bikes.append('redline')
bikes.append('giant') If-elif-else statements
Making numerical lists if age < 4:
squares = [] for x in ticket_price = 0
elif age < 18:
range(1, 11):
ticket_price = 10
squares.append(x**2)
elif age < 65:
ticket_price = 40
else:
ticket_price = 15
While loops Classes Working with files
A while loop repeats a block of code as long as a certain A class defines the behavior of an object and the kind of Your programs can read from files and write to files. The
condition is true. While loops are especially useful when you information an object can store. The information in a class pathlib library makes it easier to work with files and
can't know ahead of time how many times a loop should run. is stored in attributes, and functions that belong to a class directories. Once you have a path defined, you can
are called methods. A child class inherits the attributes and work with the read_text() and write_text()
A simple while loop methods from its parent class. methods.
current_value = 1 while
Creating a dog class Reading the contents of a file
current_value <= 5: The read_text() method reads in the entire contents of a file. You
print(current_value) can then split the text into a list of individual lines, and then process
current_value += 1 each line as you need to.
Letting the user choose when to quit
, lOMoAR cPSD| 6861666
msg = '' while msg class Dog: from pathlib import Path
!= 'quit': """Represent a dog."""
msg = input("What's your message? ") path = Path('siddhartha.txt')
def __init__(self, name): contents = path.read_text()
if msg != 'quit': """Initialize dog object.""" lines = contents.splitlines()
print(msg) self.name = name
for line in lines:
def sit(self): print(line)
"""Simulate sitting."""
Writing to a file
print(f"{self.name} is sitting.") my_dog =
Dog('Peso') path = Path('journal.txt')
print(f"{my_dog.name} is a great dog!") msg = "I love programming.")
my_dog.sit() path.write_text(msg)
Inheritance
class SARDog(Dog):
"""Represent a search dog."""
def __init__(self, name):
Functions """Initialize the sardog."""
Functions are named blocks of code, designed to do one super().__init__(name)
specific job. Information passed to a function is called an
argument, and information received by a function is called a def search(self):
parameter. """Simulate searching."""
A simple function print(f"{self.name} is searching.") my_dog = Exceptions
SARDog('Willie') Exceptions help you respond appropriately to errors that are
def greet_user(): likely to occur. You place code that might cause an error in
"""Display a simple greeting.""" the try block. Code that should run in response to an error
print(f"{my_dog.name} is a search dog.")
print("Hello!") greet_user() goes in the except block. Code that should run only if the try
my_dog.sit()
my_dog.search() block was successful goes in the else block.
Catching an exception
Passing an argument
prompt = "How many tickets do you need? "
def greet_user(username): num_tickets = input(prompt)
"""Display a personalized greeting."""
print(f"Hello, {username}!") try: num_tickets = int(num_tickets)
greet_user('jesse') except ValueError: print("Please
try again.") else: print("Your
tickets are printing.")
Default values for parameters
, lOMoAR cPSD| 6861666
def make_pizza(topping='pineapple'): Infinite Skills
"""Make a single-topping pizza."""
print(f"Have a {topping} pizza!")
If you had infinite programming skills, what would you build? Zen of Python
Simple is better than complex
As you're learning to program, it's helpful to think
make_pizza()
make_pizza('mushroom') about the real-world projects you'd like to create. It's If you have a choice between a simple and a
a good habit to keep an "ideas" notebook that you complex solution, and both work, use the simple
Returning a value can refer to whenever you want to start a new project. solution. Your code will be easier to maintain, and it
def add_numbers(x, y):
If you haven't done so already, take a few minutes will be easier for you and others to build on that code
"""Add two numbers and return the sum.""" and describe three projects you'd like to create. As later on.
return x + y you're learning you can write small programs that
relate to these ideas, so you can get practice writing
sum = add_numbers(3, 5) code relevant to topics you're interested in.
print(sum)
Adding elements Sorting a list
Beginner's Python You can add elements to the end of a list, or you can insert
them wherever you like in a list. This allows you to modify
The sort() method changes the order of a list permanently.
The sorted() function returns a copy of the list, leaving the
existing lists, or start with an empty list and then add items to original list unchanged.
Cheat Sheet - Lists it as the program develops. You can sort the items in a list in alphabetical order, or
reverse alphabetical order. You can also reverse the original
Adding an element to the end of the list order of the list. Keep in mind that lowercase and uppercase
users.append('amy') letters may affect the sort order.
What are lists?
Sorting a list permanently
A list stores a series of items in a particular order. Lists Starting with an empty list
users.sort()
allow you to store sets of information in one place, users = []
whether you have just a few items or millions of items. users.append('amy')
Sorting a list permanently in reverse alphabetical order
Lists are one of Python's most powerful features users.append('val')
readily accessible to new programmers, and they tie users.append('bob') users.sort(reverse=True)
together many important concepts in programming. users.append('mia')
Sorting a list temporarily
Inserting elements at a particular position
print(sorted(users))
Defining a list users.insert(0, 'joe') print(sorted(users, reverse=True))
Use square brackets to define a list, and use commas to users.insert(3, 'bea')
separate individual items in the list. Use plural names for Reversing the order of a list
lists, to make it clear that the variable represents more than
users.reverse()
one item. Removing elements
You can remove elements by their position in a list, or by the
Making a list
value of the item. If you remove an item by its value, Python
users = ['val', 'bob', 'mia', 'ron', 'ned'] removes only the first item that has that value.
Deleting an element by its position
del users[-1]
Removing an item by its value
Lists (cont.) Dictionaries
Beginner's Python List comprehensions
Dictionaries store connections between pieces of
information. Each item in a dictionary is a key-value pair.
Cheat Sheet squares = [x**2 for x in range(1, 11)]
Slicing a list
A simple dictionary
alien = {'color': 'green', 'points': 5}
finishers = ['sam', 'bob', 'ada', 'bea']
Accessing a value
Variables and Strings first_two = finishers[:2]
Variables are used to assign labels to values. A string is a print(f"The alien's color is
Copying a list {alien['color']}.")
series of characters, surrounded by single or double quotes.
Python's f-strings allow you to use variables inside strings to copy_of_bikes = bikes[:] Adding a new key-value pair
build dynamic messages.
alien['x_position'] = 0
Hello world
Tuples Looping through all key-value pairs
print("Hello world!") Tuples are similar to lists, but the items in a tuple can't be
modified. fav_numbers = {'eric': 7, 'ever': 4, 'erin':
Hello world with a variable 47}
msg = "Hello world!" Making a tuple
for name, number in fav_numbers.items():
print(msg) dimensions = (1920, 1080) print(f"{name} loves {number}.")
resolutions = ('720p', '1080p', '4K')
f-strings (using variables in strings) Looping through all keys
first_name = 'albert' fav_numbers = {'eric': 7, 'ever': 4, 'erin':
last_name = 'einstein' If statements 47}
full_name = f"{first_name} {last_name}" If statements are used to test for particular conditions and
print(full_name) for name in fav_numbers.keys():
respond appropriately.
print(f"{name} loves a number.")
Conditional tests Looping through all the values
fav_numbers = {'eric': 7, 'ever': 4, 'erin':
Lists 47}
A list stores a series of items in a particular order. You
access items using an index, or within a loop. for number in fav_numbers.values():
print(f"{number} is a favorite.")
, lOMoAR cPSD| 6861666
Make a list equal x == 42
not equal x != 42
bikes = ['trek', 'redline', 'giant']
greater than x > 42
User input
Your programs can prompt the user for input. All input is
or equal to x >= 42
Get the first item in a list stored as a string.
less than x < 42
first_bike = bikes[0] or equal to x <= 42 Prompting for a value
Conditional tests with lists
Get the last item in a list name = input("What's your name? ")
'trek' in bikes print(f"Hello, {name}!")
last_bike = bikes[-1]
'surly' not in bikes
Prompting for numerical input
Looping through a list
Assigning boolean values age = input("How old are you? ")
for bike in bikes: age = int(age)
game_active = True
print(bike)
can_edit = False
pi = input("What's the value of pi? ")
Adding items to a list pi = float(pi)
A simple if test
bikes = []
if age >= 18:
bikes.append('trek')
print("You can vote!")
bikes.append('redline')
bikes.append('giant') If-elif-else statements
Making numerical lists if age < 4:
squares = [] for x in ticket_price = 0
elif age < 18:
range(1, 11):
ticket_price = 10
squares.append(x**2)
elif age < 65:
ticket_price = 40
else:
ticket_price = 15
While loops Classes Working with files
A while loop repeats a block of code as long as a certain A class defines the behavior of an object and the kind of Your programs can read from files and write to files. The
condition is true. While loops are especially useful when you information an object can store. The information in a class pathlib library makes it easier to work with files and
can't know ahead of time how many times a loop should run. is stored in attributes, and functions that belong to a class directories. Once you have a path defined, you can
are called methods. A child class inherits the attributes and work with the read_text() and write_text()
A simple while loop methods from its parent class. methods.
current_value = 1 while
Creating a dog class Reading the contents of a file
current_value <= 5: The read_text() method reads in the entire contents of a file. You
print(current_value) can then split the text into a list of individual lines, and then process
current_value += 1 each line as you need to.
Letting the user choose when to quit
, lOMoAR cPSD| 6861666
msg = '' while msg class Dog: from pathlib import Path
!= 'quit': """Represent a dog."""
msg = input("What's your message? ") path = Path('siddhartha.txt')
def __init__(self, name): contents = path.read_text()
if msg != 'quit': """Initialize dog object.""" lines = contents.splitlines()
print(msg) self.name = name
for line in lines:
def sit(self): print(line)
"""Simulate sitting."""
Writing to a file
print(f"{self.name} is sitting.") my_dog =
Dog('Peso') path = Path('journal.txt')
print(f"{my_dog.name} is a great dog!") msg = "I love programming.")
my_dog.sit() path.write_text(msg)
Inheritance
class SARDog(Dog):
"""Represent a search dog."""
def __init__(self, name):
Functions """Initialize the sardog."""
Functions are named blocks of code, designed to do one super().__init__(name)
specific job. Information passed to a function is called an
argument, and information received by a function is called a def search(self):
parameter. """Simulate searching."""
A simple function print(f"{self.name} is searching.") my_dog = Exceptions
SARDog('Willie') Exceptions help you respond appropriately to errors that are
def greet_user(): likely to occur. You place code that might cause an error in
"""Display a simple greeting.""" the try block. Code that should run in response to an error
print(f"{my_dog.name} is a search dog.")
print("Hello!") greet_user() goes in the except block. Code that should run only if the try
my_dog.sit()
my_dog.search() block was successful goes in the else block.
Catching an exception
Passing an argument
prompt = "How many tickets do you need? "
def greet_user(username): num_tickets = input(prompt)
"""Display a personalized greeting."""
print(f"Hello, {username}!") try: num_tickets = int(num_tickets)
greet_user('jesse') except ValueError: print("Please
try again.") else: print("Your
tickets are printing.")
Default values for parameters
, lOMoAR cPSD| 6861666
def make_pizza(topping='pineapple'): Infinite Skills
"""Make a single-topping pizza."""
print(f"Have a {topping} pizza!")
If you had infinite programming skills, what would you build? Zen of Python
Simple is better than complex
As you're learning to program, it's helpful to think
make_pizza()
make_pizza('mushroom') about the real-world projects you'd like to create. It's If you have a choice between a simple and a
a good habit to keep an "ideas" notebook that you complex solution, and both work, use the simple
Returning a value can refer to whenever you want to start a new project. solution. Your code will be easier to maintain, and it
def add_numbers(x, y):
If you haven't done so already, take a few minutes will be easier for you and others to build on that code
"""Add two numbers and return the sum.""" and describe three projects you'd like to create. As later on.
return x + y you're learning you can write small programs that
relate to these ideas, so you can get practice writing
sum = add_numbers(3, 5) code relevant to topics you're interested in.
print(sum)
Adding elements Sorting a list
Beginner's Python You can add elements to the end of a list, or you can insert
them wherever you like in a list. This allows you to modify
The sort() method changes the order of a list permanently.
The sorted() function returns a copy of the list, leaving the
existing lists, or start with an empty list and then add items to original list unchanged.
Cheat Sheet - Lists it as the program develops. You can sort the items in a list in alphabetical order, or
reverse alphabetical order. You can also reverse the original
Adding an element to the end of the list order of the list. Keep in mind that lowercase and uppercase
users.append('amy') letters may affect the sort order.
What are lists?
Sorting a list permanently
A list stores a series of items in a particular order. Lists Starting with an empty list
users.sort()
allow you to store sets of information in one place, users = []
whether you have just a few items or millions of items. users.append('amy')
Sorting a list permanently in reverse alphabetical order
Lists are one of Python's most powerful features users.append('val')
readily accessible to new programmers, and they tie users.append('bob') users.sort(reverse=True)
together many important concepts in programming. users.append('mia')
Sorting a list temporarily
Inserting elements at a particular position
print(sorted(users))
Defining a list users.insert(0, 'joe') print(sorted(users, reverse=True))
Use square brackets to define a list, and use commas to users.insert(3, 'bea')
separate individual items in the list. Use plural names for Reversing the order of a list
lists, to make it clear that the variable represents more than
users.reverse()
one item. Removing elements
You can remove elements by their position in a list, or by the
Making a list
value of the item. If you remove an item by its value, Python
users = ['val', 'bob', 'mia', 'ron', 'ned'] removes only the first item that has that value.
Deleting an element by its position
del users[-1]
Removing an item by its value