Beginners Python Cheat Sheet PCC All
Beginners Python Cheat Sheet PCC All
List comprehensions
squares = [x**2 for x in range(1, 11)]
Slicing a list
Hello world
copy_of_bikes = bikes[:]
Make a list
bikes = ['trek', 'redline', 'giant']
Making a tuple
dimensions = (1920, 1080)
equals
not equal
greater than
or equal to
less than
or equal to
x
x
x
x
x
x
== 42
!= 42
> 42
>= 42
< 42
<= 42
first_bike = bikes[0]
'trek' in bikes
'surly' not in bikes
Conditional tests
A list stores a series of items in a particular order. You
access items using an index, or within a loop.
Accessing a value
print("The alien's color is ' + alien['color'])
Copying a list
print("Hello world!")
A simple dictionary
Boolean values
game_active = True
can_edit = False
A simple if test
if age >= 18:
print("You can vote!")
Your programs can prompt the user for input. All input is
stored as a string.
If-elif-else statements
if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else:
ticket_price = 15
A simple function
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
Passing an argument
def greet_user(username):
"""Display a personalized greeting."""
print("Hello, " + username + "!")
def make_pizza(topping='bacon'):
"""Make a single-topping pizza."""
print("Have a " + topping + " pizza!")
make_pizza()
make_pizza('pepperoni')
Returning a value
def add_numbers(x, y):
"""Add two numbers and return the sum."""
return x + y
sum = add_numbers(3, 5)
print(sum)
Writing to a file
filename = 'journal.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
Appending to a file
filename = 'journal.txt'
with open(filename, 'a') as file_object:
file_object.write("\nI love making games.")
Inheritance
class SARDog(Dog):
"""Represent a search dog."""
def __init__(self, name):
"""Initialize the sardog."""
super().__init__(name)
def search(self):
"Simulate searching."""
print(self.name + " is searching.")
greet_user('jesse')
Your programs can read from files and write to files. Files
are opened in read mode ('r') by default, but can also be
opened in write mode ('w') and append mode ('a').
my_dog = SARDog('Willie')
print(my_dog.name + " is a search dog.")
my_dog.sit()
my_dog.search()
Catching an exception
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.")
You can add elements to the end of a list, or you can insert
them wherever you like in a list.
users = []
users.append('val')
users.append('bob')
users.append('mia')
Making a list
Changing an element
users[0] = 'valerie'
users[-2] = 'ronald'
To copy a list make a slice that starts at the first item and
ends at the last item. If you try to copy a list without using
this approach, whatever you do to the copied list will affect
the original list as well.
You can work with any set of elements from a list. A portion
of a list is called a slice. To slice a list start with the index of
the first item you want, then add a colon and the index after
the last item you want. Leave off the first index to start at
the beginning of the list, and leave off the last index to slice
through the end of the list.
middle_three = finishers[1:4]
Overwriting a tuple
dimensions = (800, 600)
print(dimensions)
dimensions = (1200, 900)
Defining a tuple
Looping through a tuple
Readability counts
Making a dictionary
alien_0 = {'color': 'green', 'points': 5}
alien_0['x'] = 0
alien_0['y'] = 25
alien_0['speed'] = 1.5
del alien_0['points']
print(alien_0)
A million aliens
aliens = []
# Make a million green aliens, worth 5 points
# each. Have them all start in one row.
for alien_num in range(1000000):
new_alien = {}
new_alien['color'] = 'green'
new_alien['points'] = 5
new_alien['x'] = 20 * alien_num
new_alien['y'] = 0
aliens.append(new_alien)
# Prove the list contains a million aliens.
num_aliens = len(aliens)
print("Number of aliens created:")
print(num_aliens)
Comparison operators
>>> car
>>> car
True
>>> car
>>> car
False
= 'bmw'
== 'bmw'
= 'audi'
== 'bmw'
>>> age
>>> age
True
>>> age
True
>>> age
False
>>> age
False
= 19
< 21
Simple if statement
age = 19
if age >= 18:
print("You're old enough to vote!")
If-else statements
age = 17
<= 21
> 21
>= 21
= 22
= 18
>= 21 and age_1 >= 21
= 23
>= 21 and age_1 >= 21
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
= 22
= 18
>= 21 or age_1 >= 21
= 18
>= 21 or age_1 >= 21
You can allow your users to enter input using the input()
statement. In Python 3, all input is stored as a string.
Simple input
name = input("What's your name? ")
print("Hello, " + name + ".")
print("\nYour team:")
for player in players:
print(player)
if message != 'quit':
print(message)
Using a flag
if message == 'quit':
active = False
else:
print(message)
An infinite loop
while True:
name = input("\nWho are you? ")
print("Nice to meet you, " + name + "!")
Counting to 5
current_number = 1
players = []
while True:
player = input(prompt)
if player == 'quit':
break
elif player in banned_users:
print(player + " is banned!")
continue
else:
players.append(player)
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()
Making a function
Returning a dictionary
def build_person(first, last):
"""Return a dictionary of information
about a person.
"""
person = {'first': first, 'last': last}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
describe_pet('harry', 'hamster')
describe_pet('willie')
import pizza
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')
print("\nUnprinted:", unprinted)
print("Printed:", printed)
return profile
# Create two users with different kinds
#
of information.
user_0 = build_profile('albert', 'einstein',
location='princeton')
user_1 = build_profile('marie', 'curie',
location='paris', field='chemistry')
print(user_0)
print(user_1)
As you can see there are many ways to write and call a
function. When you're starting out, aim for something that
simply works. As you gain experience you'll develop an
understanding of the more subtle advantages of different
structures such as positional and keyword arguments, and
the various approaches to importing functions. For now if
your functions do what you need them to, you're doing well.
p.make_pizza('medium', 'pepperoni')
p.make_pizza('small', 'bacon', 'pineapple')
Calling methods
my_car.fill_tank()
my_car.drive()
A Battery class
class Battery():
"""A battery for an electric car."""
def __init__(self, size=70):
"""Initialize battery attributes."""
# Capacity in kWh, charge level in %.
self.size = size
self.charge_level = 0
def get_range(self):
"""Return the battery's range."""
if self.size == 70:
return 240
elif self.size == 85:
return 270
Class files can get long as you add detailed information and
functionality. To help keep your program files uncluttered,
you can store your classes in modules and import the
classes you need into your main program.
import car
my_beetle = car.Car(
'volkswagen', 'beetle', 2016)
my_beetle.fill_tank()
my_beetle.drive()
my_tesla = car.ElectricCar(
'tesla', 'model s', 2016)
my_tesla.charge()
my_tesla.drive()
filename = 'siddhartha.txt'
f_path = "/home/ehmatthes/books/alice.txt"
f_path = "C:\Users\ehmatthes\books\alice.txt"
To read from a file your program needs to open the file and
then read the contents of the file. You can read the entire
contents of the file at once, or read the file line by line. The
with statement makes sure the file is closed properly when
the program has finished accessing the file.
Appending to a file
filename = 'programming.txt'
with open(filename, 'a') as f:
f.write("I also love working with data.\n")
f.write("I love making apps as well.\n")
filename = 'siddhartha.txt'
with open(filename) as f_obj:
contents = f_obj.read()
print(contents)
filename = 'siddhartha.txt'
with open(filename) as f_obj:
for line in f_obj:
print(line.rstrip())
When Python runs the open() function, it looks for the file in
the same directory where the program that's being excuted
is stored. You can open a file from a subfolder using a
relative path. You can also use an absolute path to open
any file on your system.
When you think an error may occur, you can write a tryexcept block to handle the exception that might be raised.
The try block tells Python to try running some code, and the
except block tells Python what to do if the code results in a
particular kind of error.
The try block should only contain code that may cause an
error. Any code that depends on the try block running
successfully should be placed in the else block.
try:
result = int(x) / int(y)
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print(result)
try:
# Do something
except Exception:
pass
try:
# Do something
except Exception as e:
print(e, type(e))
import json
filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)
print(numbers)
When you change your code, its important to run your existing
tests. This will tell you whether the changes you made affected
existing behavior.
import unittest
from full_names import get_full_name
class NamesTestCase(unittest.TestCase):
"""Tests for names.py."""
def test_first_last(self):
"""Test names like Janis Joplin."""
full_name = get_full_name('janis',
'joplin')
self.assertEqual(full_name,
'Janis Joplin')
unittest.main()
.
--------------------------------------Ran 1 test in 0.000s
OK
A function to test
Save this as full_names.py
Failing tests are important; they tell you that a change in the
code has affected existing behavior. When a test fails, you
need to modify the code so the existing behavior still works.
E
================================================
ERROR: test_first_last (__main__.NamesTestCase)
Test names like Janis Joplin.
-----------------------------------------------Traceback (most recent call last):
File "test_full_names.py", line 10,
in test_first_last
'joplin')
TypeError: get_full_name() missing 1 required
positional argument: 'last'
-----------------------------------------------Ran 1 test in 0.001s
FAILED (errors=1)
.
--------------------------------------Ran 1 test in 0.000s
OK
You can add as many unit tests to a test case as you need.
To write a new test, add a new method to your test case
class.
Save as accountant.py
A class to test
class Accountant():
"""Manage a bank account."""
import unittest
from full_names import get_full_name
class NamesTestCase(unittest.TestCase):
"""Tests for names.py."""
def test_first_last(self):
"""Test names like Janis Joplin."""
full_name = get_full_name('janis',
'joplin')
self.assertEqual(full_name,
'Janis Joplin')
def test_middle(self):
"""Test names like David Lee Roth."""
full_name = get_full_name('david',
'roth', 'lee')
self.assertEqual(full_name,
'David Lee Roth')
import unittest
from accountant import Accountant
class TestAccountant(unittest.TestCase):
"""Tests for the class Accountant."""
def setUp(self):
self.acc = Accountant()
def test_initial_balance(self):
# Default balance should be 0.
self.assertEqual(self.acc.balance, 0)
Building a testcase
For the first test, well make sure we can start out with different
initial balances. Save this as test_accountant.py.
import unittest
from accountant import Accountant
class TestAccountant(unittest.TestCase):
"""Tests for the class Accountant."""
def test_deposit(self):
# Test single deposit.
self.acc.deposit(100)
self.assertEqual(self.acc.balance, 100)
def test_initial_balance(self):
# Default balance should be 0.
acc = Accountant()
self.assertEqual(acc.balance, 0)
unittest.main()
..
--------------------------------------Ran 2 tests in 0.000s
OK
def test_withdrawal(self):
# Test single withdrawal.
self.acc.deposit(1000)
self.acc.withdraw(100)
self.assertEqual(self.acc.balance, 900)
unittest.main()
.
--------------------------------------Ran 1 test in 0.000s
OK
unittest.main()
Pygame on Linux
$ sudo apt-get install python3-dev mercurial
libsdl-image1.2-dev libsdl2-dev
libsdl-ttf2.0-dev
$ pip install --user
hg+http://bitbucket.org/pygame/pygame
Pygame on OS X
This assumes youve used Homebrew to install Python 3.
Pygame on Windows
Find an installer at
https://bitbucket.org/pygame/pygame/downloads/ or
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame that matches
your version of Python. Run the installer file if its a .exe or .msi file.
If its a .whl file, use pip to install Pygame:
$ python
>>> import pygame
>>>
def run_game():
# Initialize and set up screen.
pg.init()
screen = pg.display.set_mode((1200, 800))
pg.display.set_caption("Alien Invasion")
# Start main loop.
while True:
# Start event loop.
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
# Refresh screen.
pg.display.flip()
run_game()
Loading an image
ship = pg.image.load('images/ship.bmp')
Positioning an image
Many objects in a game can be treated as simple
rectangles, rather than their actual shape. This simplifies
code without noticeably affecting game play. Pygame has a
rect object that makes it easy to work with game objects.
With rects, its easy to position an image wherever you want on the
screen, or in relation to another object. The following code
positions a ship object at the bottom center of the screen.
ship_rect.midbottom = screen_rect.midbottom
screen_rect = screen.get_rect()
screen_center = screen_rect.center
def blitme(self):
"""Draw ship at current location."""
self.screen.blit(self.image, self.rect)
mouse_pos = pg.mouse.get_pos()
Clicking a button
You might want to know if the cursor is over an object such as a
button. The rect.collidepoint() method returns true when a point is
inside a rect object.
if button_rect.collidepoint(mouse_pos):
start_game()
if event.type == pg.KEYUP:
if event.key == pg.K_RIGHT:
ship.moving_right = False
Its important to delete elements that will never appear again in the
game, so you dont waste memory and resources.
bullets.remove(bullet)
if pg.sprite.spritecollideany(ship, aliens):
ships_left -= 1
collisions = pg.sprite.groupcollide(
bullets, aliens, True, True)
Pygame has a Group class which makes working with a
group of similar objects easier. A group is like a list, with
some extra functionality thats helpful when building games.
bullets.update()
Displaying a message
The following code defines a message, then a color for the text and
the background color for the message. A font is defined using the
default system font, with a font size of 48. The font.render()
function is used to create an image of the message, and we get the
rect object associated with the image. We then center the image
on the screen and display it.
Emphasizing points
You can plot as much data as you want on one plot. Here we replot the first and last points larger to emphasize them.
x_values = list(range(1000))
squares = [x**2 for x in x_values]
plt.scatter(x_values, squares, c=squares,
cmap=plt.cm.Blues, edgecolor='none',
s=10)
plt.scatter(x_values[0], squares[0], c='green',
edgecolor='none', s=100)
plt.scatter(x_values[-1], squares[-1], c='red',
edgecolor='none', s=100)
plt.title("Square Numbers", fontsize=24)
--snip--
Removing axes
matplotlib runs on all systems, but setup is slightly different
depending on your OS. If the minimal instructions here
dont work for you, see the more detailed instructions at
http://ehmatthes.github.io/pcc/. You should also consider
installing the Anaconda distrubution of Python from
https://continuum.io/downloads/, which includes matplotlib.
matplotlib on Linux
$ sudo apt-get install python3-matplotlib
matplotlib on OS X
Start a terminal session and enter import matplotlib to see if
its already installed on your system. If not, try this command:
matplotlib on Windows
You first need to install Visual Studio, which you can do from
https://dev.windows.com/. The Community edition is free. Then go
to https://pypi.python.org/pypi/matplotlib/ or
http://www.lfd.uic.edu/~gohlke/pythonlibs/#matplotlib and download
an appropriate installer file.
x_values = list(range(1000))
squares = [x**2 for x in x_values]
plt.scatter(x_values, squares, s=10)
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=18)
plt.ylabel("Square of Value", fontsize=18)
plt.tick_params(axis='both', which='major',
labelsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
Using a colormap
A colormap varies the point colors from one shade to another,
based on a certain value for each point. The value used to
determine the color of each point is passed to the c argument, and
the cmap argument specifies which colormap to use.
The edgecolor='none' argument removes the black outline
from each point.
Saving a plot
The matplotlib viewer has an interactive save button, but you can
also save your visualizations programmatically. To do so, replace
plt.show() with plt.savefig(). The bbox_inches='tight'
argument trims extra whitespace from the plot.
plt.savefig('squares.png', bbox_inches='tight')
Many interesting data sets have a date or time as the xvalue. Pythons datetime module helps you work with this
kind of data.
%A
%B
%m
%d
%Y
%y
%H
%I
%p
%M
%S
Sharing an x-axis
The following code plots a set of squares and a set of cubes on
two separate graphs that share a common x-axis.
The plt.subplots() function returns a figure object and a tuple
of axes. Each set of axes corresponds to a separate plot in the
figure. The first two arguments control the number of rows and
columns generated in the figure.
axarr[0].scatter(x_vals, squares)
axarr[0].set_title('Squares')
Sharing a y-axis
To share a y-axis, we use the sharey=True argument.
x_vals = list(range(11))
squares = [x**2 for x in x_vals]
cubes = [x**3 for x in x_vals]
dates = [
dt(2016, 6, 21), dt(2016, 6, 22),
dt(2016, 6, 23), dt(2016, 6, 24),
]
highs = [57, 68, 64, 59]
fig = plt.figure(dpi=128, figsize=(10,6))
plt.plot(dates, highs, c='red')
plt.title("Daily High Temps", fontsize=24)
plt.ylabel("Temp (F)", fontsize=16)
x_axis = plt.axes().get_xaxis()
x_axis.set_major_formatter(
mdates.DateFormatter('%B %d %Y')
)
fig.autofmt_xdate()
plt.show()
import pygal
squares = [
(0, 0), (1, 1), (2, 4), (3, 9),
(4, 16), (5, 25),
]
chart = pygal.XY(stroke=False)
chart.force_uri_protocol = 'http'
chart.add('x^2', squares)
chart.render_to_file('squares.svg')
Pygal on Windows
> python m pip install --user pygal
To make a plot with Pygal, you specify the kind of plot and
then add the data.
import pygal
x_values = [0, 1, 2, 3, 4, 5]
squares = [0, 1, 4, 9, 16, 25]
chart = pygal.Line()
chart.force_uri_protocol = 'http'
chart.add('x^2', squares)
chart.render_to_file('squares.svg')
import pygal
outcomes = [1, 2, 3, 4, 5, 6]
frequencies = [18, 16, 18, 17, 18, 13]
chart = pygal.Bar()
chart.force_uri_protocol = 'http'
chart.x_labels = outcomes
chart.add('D6', frequencies)
chart.render_to_file('rolling_dice.svg')
import pygal
results = {
1:18, 2:16, 3:18,
4:17, 5:18, 6:13,
}
chart = pygal.Bar()
chart.force_uri_protocol = 'http'
chart.x_labels = results.keys()
chart.add('D6', results.values())
chart.render_to_file('rolling_dice.svg')
import pygal
from pygal.style import LightGreenStyle
x_values = list(range(11))
squares = [x**2 for x in x_values]
cubes = [x**3 for x in x_values]
chart_style = LightGreenStyle()
chart = pygal.Line(style=chart_style)
chart.force_uri_protocol = 'http'
chart.title = "Squares and Cubes"
chart.x_labels = x_values
chart.add('Squares', squares)
chart.add('Cubes', cubes)
chart.render_to_file('squares_cubes.svg')
chart_style = LightenStyle('#336688')
chart_style.plot_background = '#CCCCCC'
chart_style.major_label_font_size = 20
chart_style.label_font_size = 16
--snip--
chart_style = Style()
chart_style.colors = [
'#CCCCCC', '#AAAAAA', '#888888']
chart_style.plot_background = '#EEEEEE'
chart = pygal.Line(style=chart_style)
--snip--
Configuration settings
Some settings are controlled by a Config object.
my_config = pygal.Config()
my_config.show_y_guides = False
my_config.width = 1000
my_config.dots_size = 5
chart = pygal.Line(config=my_config)
--snip--
Styling series
You can give each series on a chart different style settings.
import pygal
repos = [
{
'value': 20506,
'color': '#3333CC',
'xlink': 'http://djangoproject.com/',
},
20054,
12607,
11827,
]
chart = pygal.Bar()
chart.force_uri_protocol = 'http'
chart.x_labels = [
'django', 'requests', 'scikit-learn',
'tornado',
]
chart.y_title = 'Stars'
chart.add('Python Repos', repos)
chart.render_to_file('python_repos.svg')
Pygal can generate world maps, and you can add any data
you want to these maps. Data is indicated by coloring, by
labels, and by tooltips that show data when users hover
over each country on the map.