Beginners Python Cheat Sheets Sample
Beginners Python Cheat Sheets Sample
) Dictionaries
Beginner's Python List comprehensions Dictionaries store connections between pieces of
information. Each item in a dictionary is a key-value pair.
squares = [x**2 for x in range(1, 11)]
Cheat Sheet Slicing a list
A simple dictionary
alien = {'color': 'green', 'points': 5}
finishers = ['sam', 'bob', 'ada', 'bea']
first_two = finishers[:2] Accessing a value
Variables and Strings
Copying a list print(f"The alien's color is {alien['color']}.")
Variables are used to assign labels to values. A string is a
series of characters, surrounded by single or double quotes. copy_of_bikes = bikes[:] Adding a new key-value pair
Python's f-strings allow you to use variables inside strings to
alien['x_position'] = 0
build dynamic messages.
Tuples
Hello world Looping through all key-value pairs
Tuples are similar to lists, but the items in a tuple can't be
print("Hello world!") modified. fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
Hello world with a variable Making a tuple for name, number in fav_numbers.items():
dimensions = (1920, 1080) print(f"{name} loves {number}.")
msg = "Hello world!"
resolutions = ('720p', '1080p', '4K')
print(msg) Looping through all keys
f-strings (using variables in strings) If statements fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
first_name = 'albert' If statements are used to test for particular conditions and for name in fav_numbers.keys():
last_name = 'einstein' respond appropriately. print(f"{name} loves a number.")
full_name = f"{first_name} {last_name}"
print(full_name) Conditional tests Looping through all the values
equal x == 42
fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
Lists not equal x != 42
A list stores a series of items in a particular order. You greater than x > 42
for number in fav_numbers.values():
or equal to x >= 42
access items using an index, or within a loop. print(f"{number} is a favorite.")
less than x < 42
Make a list or equal to x <= 42
User input
bikes = ['trek', 'redline', 'giant'] Conditional tests with lists Your programs can prompt the user for input. All input is
Get the first item in a list 'trek' in bikes stored as a string.
'surly' not in bikes
first_bike = bikes[0] Prompting for a value
Assigning boolean values
Get the last item in a list name = input("What's your name? ")
game_active = True print(f"Hello, {name}!")
last_bike = bikes[-1]
can_edit = False
Prompting for numerical input
Looping through a list
A simple if test age = input("How old are you? ")
for bike in bikes: age = int(age)
if age >= 18:
print(bike)
print("You can vote!")
Adding items to a list pi = input("What's the value of pi? ")
If-elif-else statements pi = float(pi)
bikes = []
if age < 4:
bikes.append('trek')
ticket_price = 0
bikes.append('redline')
elif age < 18:
bikes.append('giant')
ticket_price = 10 Python Crash Course
Making numerical lists elif age < 65: A Hands-on, Project-Based
ticket_price = 40 Introduction to Programming
squares = [] else:
for x in range(1, 11): ticket_price = 15 nostarch.com/pythoncrashcourse2e
squares.append(x**2)
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. Files
condition is true. While loops are especially useful when you information an object can store. The information in a class are opened in read mode by default, but can also be opened
can't know ahead of time how many times a loop should run. is stored in attributes, and functions that belong to a class in write mode and append mode.
are called methods. A child class inherits the attributes and
A simple while loop Reading a file and storing its lines
methods from its parent class.
current_value = 1 filename = 'siddhartha.txt'
while current_value <= 5: Creating a dog class with open(filename) as file_object:
print(current_value) class Dog: lines = file_object.readlines()
current_value += 1 """Represent a dog."""
for line in lines:
Letting the user choose when to quit def __init__(self, name): print(line)
msg = '' """Initialize dog object."""
while msg != 'quit': self.name = name Writing to a file
The variable referring to the file object is often shortened to f.
msg = input("What's your message? ")
print(msg) def sit(self): filename = 'journal.txt'
"""Simulate sitting.""" with open(filename, 'w') as f:
Functions print(f"{self.name} is sitting.") f.write("I love programming.")
Functions are named blocks of code, designed to do one my_dog = Dog('Peso') Appending to a file
specific job. Information passed to a function is called an
filename = 'journal.txt'
argument, and information received by a function is called a print(f"{my_dog.name} is a great dog!") with open(filename, 'a') as f:
parameter. my_dog.sit() f.write("\nI love making games.")
A simple function Inheritance
def greet_user(): class SARDog(Dog):
Exceptions
"""Display a simple greeting.""" """Represent a search dog.""" Exceptions help you respond appropriately to errors that are
print("Hello!") likely to occur. You place code that might cause an error in
def __init__(self, name): the try block. Code that should run in response to an error
greet_user() """Initialize the sardog.""" goes in the except block. Code that should run only if the try
Passing an argument super().__init__(name) block was successful goes in the else block.
Hello world with a variable Making a tuple for name, number in fav_numbers.items():
dimensions = (1920, 1080) print(f"{name} loves {number}.")
msg = "Hello world!"
resolutions = ('720p', '1080p', '4K')
print(msg) Looping through all keys
f-strings (using variables in strings) If statements fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
first_name = 'albert' If statements are used to test for particular conditions and for name in fav_numbers.keys():
last_name = 'einstein' respond appropriately. print(f"{name} loves a number.")
full_name = f"{first_name} {last_name}"
print(full_name) Conditional tests Looping through all the values
equal x == 42
fav_numbers = {'eric': 7, 'ever': 4, 'erin': 47}
Lists not equal x != 42
A list stores a series of items in a particular order. You greater than x > 42
for number in fav_numbers.values():
or equal to x >= 42
access items using an index, or within a loop. print(f"{number} is a favorite.")
less than x < 42
Make a list or equal to x <= 42
User input
bikes = ['trek', 'redline', 'giant'] Conditional tests with lists Your programs can prompt the user for input. All input is
Get the first item in a list 'trek' in bikes stored as a string.
'surly' not in bikes
first_bike = bikes[0] Prompting for a value
Assigning boolean values
Get the last item in a list name = input("What's your name? ")
game_active = True print(f"Hello, {name}!")
last_bike = bikes[-1]
can_edit = False
Prompting for numerical input
Looping through a list
A simple if test age = input("How old are you? ")
for bike in bikes: age = int(age)
if age >= 18:
print(bike)
print("You can vote!")
Adding items to a list pi = input("What's the value of pi? ")
If-elif-else statements pi = float(pi)
bikes = []
if age < 4:
bikes.append('trek')
ticket_price = 0
bikes.append('redline')
elif age < 18:
bikes.append('giant')
ticket_price = 10 Python Crash Course
Making numerical lists elif age < 65: A Hands-on, Project-Based
ticket_price = 40 Introduction to Programming
squares = [] else:
for x in range(1, 11): ticket_price = 15 nostarch.com/pythoncrashcourse2e
squares.append(x**2)
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. Files
condition is true. While loops are especially useful when you information an object can store. The information in a class are opened in read mode by default, but can also be opened
can't know ahead of time how many times a loop should run. is stored in attributes, and functions that belong to a class in write mode and append mode.
are called methods. A child class inherits the attributes and
A simple while loop Reading a file and storing its lines
methods from its parent class.
current_value = 1 filename = 'siddhartha.txt'
while current_value <= 5: Creating a dog class with open(filename) as file_object:
print(current_value) class Dog: lines = file_object.readlines()
current_value += 1 """Represent a dog."""
for line in lines:
Letting the user choose when to quit def __init__(self, name): print(line)
msg = '' """Initialize dog object."""
while msg != 'quit': self.name = name Writing to a file
The variable referring to the file object is often shortened to f.
msg = input("What's your message? ")
print(msg) def sit(self): filename = 'journal.txt'
"""Simulate sitting.""" with open(filename, 'w') as f:
Functions print(f"{self.name} is sitting.") f.write("I love programming.")
Functions are named blocks of code, designed to do one my_dog = Dog('Peso') Appending to a file
specific job. Information passed to a function is called an
filename = 'journal.txt'
argument, and information received by a function is called a print(f"{my_dog.name} is a great dog!") with open(filename, 'a') as f:
parameter. my_dog.sit() f.write("\nI love making games.")
A simple function Inheritance
def greet_user(): class SARDog(Dog):
Exceptions
"""Display a simple greeting.""" """Represent a search dog.""" Exceptions help you respond appropriately to errors that are
print("Hello!") likely to occur. You place code that might cause an error in
def __init__(self, name): the try block. Code that should run in response to an error
greet_user() """Initialize the sardog.""" goes in the except block. Code that should run only if the try
Passing an argument super().__init__(name) block was successful goes in the else block.