Professional Documents
Culture Documents
Python Cheat Sheet
Python Cheat Sheet
C
If-elif-else statements
if age < 4:
ticket_price = 0
elif age < 18: overs Python 3 and Python 2
ticket_price = 10
else:
ticket_price = 15
C
def make_pizza(topping='bacon'):
"""Make a single-topping pizza.""" You can add elements to the end of a list, or you can insert The sort() method changes the order of a list permanently.
A list stores a series of itemsIf in
themyoua particular
had youorder.
infinite
wherever programming
like in a list. skills, what would you The sorted() function returns a copy of the list, leaving the
print("Have a " + topping + " pizza!")
Lists allow you to store setsbuild?
of information in one Simple list
original is better than complex
unchanged. You can sort the items in a list in
Adding an element to the end of the list
place, whether you have just a few items or millions alphabetical order, or reverse alphabetical order. You can
make_pizza() As you're learning to program, it's helpful to think If you have a choice between a simple and a complex
make_pizza('pepperoni') of items. Lists are one of Python's
You most
canthe
remove powerful
users.append('amy') elements by their position also reverse the original order of the list. Keep in mind that
Use square brackets to define a list, and use commas to about real-world projects you'd likeintoacreate.
list, or by
It's a solution, and
lowercase both work,letters
and uppercase use the
maysimple solution.
affect the Your
sort order.
features readily accessible the
to new
value programmers,
of the item. Ifanandremove an item by its value,
you
Returning
separate a value
individual items in the list. Use plural names for Starting withtoankeep
good habit empty list
"ideas" notebook that you can code will be easier to maintain, and it will be easier
they tie together many important
Pythonconcepts in the first item that has that value.
lists, to make your code easier to read.
def add_numbers(x, y): refer toremoves
users =whenever
[]
only
you want to start a new project. If Sorting
for you aand
list others
permanently
to build on that code later on.
programming.
Making"""Add
a list two numbers and return the sum.""" you haven't
Deleting done
an element by
users.append('val') so already, take a few minutes and
its position users.sort()
return x + y describe three projects you'd like to create.
users.append('bob')
del users[-1] Lists canacontain millions of items, so Python provides an
users = ['val', 'bob', 'mia', 'ron', 'ned'] Sorting list permanently in reverse alphabetical
users.append('mia') efficient way to loop through all the items in a list. When
sum = add_numbers(3, 5) Removing an item by its value order
you set up a loop, Python pulls each item from the list one
print(sum) Inserting elements at a particular position atusers.sort(reverse=True)
a time and stores it in a temporary variable, which you
users.remove('mia')
Individual elements in a list are accessed according to their users.insert(0, 'joe') provide a name for. This name should be the singular
position, called the index. The index of the first element is Sortingofa the
version list list
temporarily
name.
users.insert(3, 'bea')
0, the index of the second element is 1, and so forth. The indented block of code makes up the body of the
print(sorted(users))
Negative indices refer to items at the end of the list. To get If you want to work with an element that you're removing loop, where you can work with each individual item. Any
print(sorted(users, reverse=True))
a particular element, write the name of the list and then the from the list, you can "pop" the element. If you think of the lines that are not indented run after the loop is completed.
index of the element in square brackets. list as a stack of items, pop() takes an item off the top of the Reversing the order of a list
Printing all items in a list
stack. By default pop() returns the last element in the list,
Getting the first element users.reverse()
but you can also pop elements from any position in the list. for user in users:
first_user = users[0] print(user)
Pop the last item from a list
Getting the second element Printing a message for each item, and a separate
most_recent_user = users.pop()
print(most_recent_user) message afterwards
second_user = users[1]
for user in users:
Getting the last element Pop the first item in a list print("Welcome, " + user + "!")
newest_user = users[-1] first_user = users.pop(0)
print(first_user) print("Welcome, we're glad to see you all!")
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
C
ems dogs = []
Use curly braces to define a dictionary. Use colons to You can
You can store
modify asthe
manyvalue associated
key-value with
pairs as any
you key
wantinina a
dogs.append('willie') You can loop through a dictionary in three ways: you can
'abe', 'ada',
connect 'gus',
keys and 'zoe']
values, and use commas to separate dictionary,
dictionary. until
To do your computer
so give runs of
the name out of
the memory.
dictionary
dogs.append('hootz')To
andadd a loop through all the key-value pairs, all the keys, or all the
hers[:3]
individual key-value pairs. Readability counts new key-value
enclose the keypair to an existing
in square dictionary
brackets, give the
then provide thename
dogs.append('peso') new values.
of the dictionary
value for that key. and the new key in dogs.append('goblin')
square brackets, and A dictionary only tracks the connections between keys
Making a dictionary
e items • Use four spaces per indentation set it equal level.
to the new value. and values; it doesn't track the order of items in the
for dog in dogs:
• 'points':
Keep your5} Modifying
This also
lines to 79 characters orvalues
allows
fewer.youin atodictionary
start with an empty dictionary
print("Hello " + and
dog + dictionary. If you want to process the information in order,
"!")
alien_0 = {'color': 'green',To
shers[1:4] access the value associated with an individual key givebecome relevant.
• Use
the namesingle
of theblank
dictionary toadd
linesand groupkey-value
alien_0
then placeparts
=the pairs
of your
{'color':
key
as they'green',
in a set of print("I
'points': love
5} these dogs!")you can sort the keys in your loop.
ems program visually. print(alien_0)
square brackets. Adding
If the key you're a key-value
asking for is not inpair
the Looping through all key-value pairs
ers[-3:] dictionary, an error will occur. print("\nThese were my first two
alien_0
# Change
You can also use the get() method, = the
which {'color':
alien's
returns None'green',
color and 'points':
dogs:") 5}
pointold_dogs = dogs[:2] for old_dog
# Store people's favorite
value.
instead of an error if the key doesn't alien_0['color']
exist. You can also in old_dogs:
= 'yellow' print(old_dog)
languages. fav_languages =
Python's dictionaries allow you tospecify
connecta pieces value to use ifalien_0['x']
default of the key is not in=the
alien_0['points'] 0 = 10 print(alien_0) { 'jen': 'python',
related information. Each piece ofdictionary.
information in a alien_0['y'] = 25 del dogs[0] 'sarah': 'c',
dictionary is stored as a key-value pair. When you alien_0['speed'] = 1.5 dogs.remove('peso')
You can remove any key-value pair you want from a 'edward': 'ruby',
provide a key, Python returns the Getting the value associated with a key print(dogs) 'phil': 'python',
value associated dictionary. To do so use
Adding to an empty dictionary the del keyword and the dictionary
You can
} find the number of key-value pairs in a dictionary.
with that key. You can loop through allalien_0
the key
-value
= {'color': 'green', name, followed
'points': by the
5} key in square brackets. This will
pairs, all the keys, or all the values. alien_0 = {}
delete the key and its associated value. Finding a dictionary's length
print(alien_0['color']) alien_0['color'] = 'green' # Show each person's favorite language. for
Deleting a key-value =pair
alien_0['points'] 5 num_responses
name, language=in len(fav_languages)
fav_languages.items():
print(alien_0['points'])
alien_0 = {'color': 'green', 'points': 5} print(name + ": " + language)
Getting the value with get() print(alien_0)
Looping through all the keys
alien_0 = {'color': 'green'}
del alien_0['points'] # Show everyone who's taken the survey. for
print(alien_0)
alien_color = alien_0.get('color') name in fav_languages.keys():
overs Python 3 and Python 2
print(name)
alien_points = alien_0.get('points', 0)
Looping through all the values
print(alien_color) Try running some of these examples on pythontutor.com.
print(alien_points) # Show all the languages that have been chosen.
for language in fav_languages.values():
print(language)
Looping through all the keys in order
# Show each person's favorite language,
# in order by the person's name. for
name in sorted(fav_languages.keys()):
print(name + ": " + language)
Testing numerical values is similar to testing string values. Several kinds of if statements exist. Your choice of which to
If statements allow you to examine the current state use depends on the number of conditions you need to test.
of a program and respond appropriately to that state. Testing equality and inequality You can have as many elif blocks as you need, and the
You can write a simple if statement that checks one >>> age = 18 else block is always optional.
condition, or you can create a complex series of if >>> age == 18
statements that idenitfy the exact conditions you're Simple if statement
True
looking for. >>> age != 18 age = 19
False if age >= 18: print("You're old
While loops run as long as certain conditions remain enough to vote!")
true. You can use while loops to let your programs run Comparison operators
as long as your users want them to. >>> age = 19 If-else statements
>>> age < 21
age = 17
True
if age >= 18: print("You're old
>>> age <= 21
enough to vote!") else: print("You
True
can't vote yet.")
>>> age > 21
False
>>> age >= 21
False The if-elif-else chain
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 + ".")
Accepting numerical input
age = input("How old are you? ") age
= int(age)
if age >= 18: print("\nYou
can vote!") else:
print("\nYou can't vote yet.")
C
def describe_pet(name, animal='dog'):
You
Sometimes
can pass
"""Display you
ainformation
list
won't
as know
an argument
how many
about toaaarguments
function, and
pet.""" a the You can store your functions in a separate file called a
Information that's passed to a function is called an function will
can need
work to
withaccept.
the Python
values
print("\nI have a " + animal + ".") in allows
the list.you
Any to collect
changes an Try runningand
module, some of these
then examples
import on pythontutor.com.
the functions you need into the file
argument; information that's received by a function is called arbitrary
the number
function
print("Its makes of to
name arguments
the"list
is into
+ will
name one
affect parameter
the
+ ".") original using
list. You containing your main program. This allows for cleaner
a parameter. Arguments are included in parentheses after the *prevent
can operator. A parameter
a function from that accepts
modifying an by
a list arbitrary
passing a program files. (Make sure your module is stored in the
the function's name, and parameters are listed in number
copy of arguments must
of the list as an argument. come last in the function
describe_pet('harry', 'hamster') same directory as your main program.)
parentheses in the function's definition. definition.
describe_pet('willie')
Passing a list as allows
The ** operator an argument
a parameter to collect an arbitrary
Storing a function in a module
File: pizza.py
overs Python 3 and Python 2
Passing a single argument number
Using of keyword
None to makearguments.
an argument optional
def greet_users(names): def make_pizza(size, *toppings):
def greet_user(username): def """Print
Collecting a simple
an arbitrary
describe_pet(animal, greeting
number to
of arguments
name=None): """Make a pizza."""
"""Display a simple greeting.""" everyone."""
"""Display information for name in names:
about a pet."""
def = make_pizza(size, *toppings): print("\nMaking a " + size + "
print("Hello, " + username + "!") msg "Hello,
print("\nI have" +a name + "!" + ".")
" + animal
"""Make
print(msg) a pizza.""" pizza.") print("Toppings:") for
if name: print("Its name is " +
topping in toppings: print("- " +
greet_user('jesse') nameprint("\nMaking
+ ".") a " + size + "
greet_user('diana') pizza.") = ['hannah',
usernames print("Toppings:")
'ty', 'margot'] for topping)
greet_user('brandon') topping in toppings:
greet_users(usernames)
describe_pet('hamster', 'harry') print("- " + Importing an entire module
topping) File: making_pizzas.py
describe_pet('snake')
Allowing a function to modify a list Every function in the module is available in the program file.
# Make
The three
following pizzas
example sendswith
a list ofdifferent toppings.
models to a function for
import pizza
As you can see there are many ways to write and call a make_pizza('small',
printing. 'pepperoni')
The original list is emptied, and the second list is filled.
function. When you're starting out, aim for something that make_pizza('large', 'bacon bits', 'pineapple')
def print_models(unprinted, printed): pizza.make_pizza('medium', 'pepperoni')
make_pizza('medium', 'mushrooms', 'peppers',
simply works. As you gain experience you'll develop an """3d print a set of models.""" while pizza.make_pizza('small', 'bacon', 'pineapple')
'onions', 'extra cheese')=
understanding of the more subtle advantages of different unprinted: current_model
unprinted.pop()
structures such as positional and keyword arguments, and the Collecting print("Printing
an arbitrary number "
of keyword arguments
various approaches to importing functions. For now if your + current_model)
functions do what you need them to, you're doing well. def build_profile(first, last, **user_info):
printed.append(current_model)
"""Build a user's profile dictionary."""
# Build
# Store some aunprinted
dict withdesigns,
the required keys.
profile = {'first': first, 'last': last}
# and print each of them. unprinted =
['phone case', 'pendant', 'ring'] printed =
You can modify an attribute's value directly, or you can write methods that manage updating values more carefully.
[] # Add any other keys and values.
for key, value in user_info.items():
print_models(unprinted, printed)
Modifying an attribute directly profile[key] = value
print("\nUnprinted:",
my_new_car = Car('audi', 'a4', 2016) my_new_car.fuel_level = 5 profile unprinted)
return
print("Printed:", printed)
print_models(original[:], printed)
print("\nOriginal:", original) More cheat sheets available at
print("Printed:", printed)
def add_fuel(self, amount): """Add fuel to the tank.""" if (self.fuel_level + amount <= self.fuel_capacity): self.fuel_level
+= amount print("Added fuel.") else: print("The tank won't hold that much.")
my_ecar.charge()
my_ecar.drive()
C
Consider how we might model a car. What information
Overriding parent methods Creating an object from a class
would we associate with a car, and what behavior would it
class ElectricCar(Car): have?
my_car The=information
Car('audi', is stored
'a4',in variables
2016) called
--snip-- def attributes, and the behavior is represented by functions.
fill_tank(self): Accessing
Functions attribute
that are partvalues
of a class are called methods.
"""Display an error message.""" print(my_car.make)
The Car class
print("This car has no fuel tank!") print(my_car.model)
class Car():
print(my_car.year)
"""A simple attempt to model a car."""
Calling methods
def __init__(self, make, model,
year):
my_car.fill_tank() """Initialize car
attributes."""
my_car.drive() self.make = make
self.model = model self.year =
Creating
year multiple objects
my_car = Car('audi', 'a4', 2016)
# Fuel capacity and level in
my_old_car = Car('subaru', 'outback', 2013)
gallons. self.fuel_capacity = 15
my_truck = Car('toyota',
self.fuel_level = 0 'tacoma', 2010)
def
fill_tank(self):
"""Fill gas tank to capacity."""
self.fuel_level = self.fuel_capacity
print("Fuel tank is full.")
def
drive(self):
"""Simulate driving."""
print("The car is moving.")
There are many ways to model real world objects and situations in code, and sometimes that variety can feel overwhelming. Pick an approach and try it – if your first attempt doesn't work,
try a different approach.
In Python class names are written in CamelCase and object names are written in lowercase with underscores. Modules that contain classes should still be named in lowercase with
underscores.
import json
Well-written, properly tested code is not very prone to numbers = [2, 3, 5, 7, 11, 13]
internal errors such as syntax or logical errors. But every
time your program depends on something external such
filename = 'numbers.json' with
as user input or the existence of a file, there's a possibility
open(filename, 'w') as f_obj:
of an exception being raised.
json.dump(numbers, f_obj)
It's up to you how to communicate errors to your users. Using json.load() to read data
Sometimes users need to know if a file is missing;
sometimes it's better to handle the error silently. A little
experience will help you know how much to report. More cheat sheets available at
"""Load some previously stored numbers.""" Practice with exceptions
Take a program you've already written that prompts for
import json user input, and add some error-handling code to the
When you write a function or a class, you can also Building a testcase with one unit test program.
write tests for that code. Testing proves that your To build a test case, make a class that inherits from
filename = 'numbers.json' unittest.TestCase and write methods that begin with test_.
code
withworks as it's supposed
open(filename) to in the situations it's
as f_obj:
designed to handle, and also when people use your Save this as test_full_names.py More cheat sheets available at
numbers = json.load(f_obj)
programs in unexpected ways. Writing tests gives import unittest Running the test
from full_names import get_full_name When you change your code, it’s important to run your existing
you confidence that your code will work correctly as
print(numbers) tests. This will tell you whether the changes you made affected
more people begin to use your programs. You can class
existing behavior.
Making
also addsure
new the storedtodata
features yourexists
programs and know NamesTestCase(unittest.TestCase):
"""Tests for names.py.""" E
that you haven't
import json broken existing behavior.
def =============================================
test_first_last(self): === ERROR: test_first_last
Af_name
unit test= verifies that one specific aspect of your
'numbers.json' """Test names like Janis Joplin.""" (__main__.NamesTestCase)
code
try:works as it's supposed to. Aas
with open(f_name) test case is a
f_obj: full_name = get_full_name('janis', Test names like Janis Joplin.
collection of unit tests which verify your code's
numbers = json.load(f_obj) except 'joplin') ---------------------------------------------
FileNotFoundError:
behavior in a wide variety ofmsg = "Can’t find
situations. self.assertEqual(full_name, ---
{0}.".format(f_name) print(msg) else: 'Janis Joplin') Traceback (most recent call last):
print(numbers) File "test_full_names.py", line 10,
unittest.main() in test_first_last
Running the test 'joplin')
Python reports on each unit test in the test case. The dot reports a TypeError: get_full_name() missing 1 required
single passing test. Python informs us that it ran 1 test in less than positional argument: 'last'
0.001 seconds, and the OK lets us know that all unit tests in the
test case passed. ---------------------------------------------
. ---
--------------------------------------- Ran 1 test in 0.001s
Ran 1 test in 0.000s
FAILED (errors=1)
Python's unittest module provides tools for testing your OK
Fixing the code
code. To try it out, we’ll create a function that returns a full
name. We’ll use the function in a regular program, and then When a test fails, the code needs to be modified until the test
build a test case for the function. passes again. (Don’t make the mistake of rewriting your tests
Failing tests are important; they tell you that a change in the to fit your new code.) Here we can make the middle name
A function to test code has affected existing behavior. When a test fails, you optional. def get_full_name(first, last,
Save this as full_names.py need to modify the code so the existing behavior still works. middle=''): """Return a full name."""
def get_full_name(first, last): if middle: full_name = "{0} {1}
Modifying the function {2}".format(first,
"""Return a full name.""" We’ll modify get_full_name() so it handles middle names, but
full_name = "{0} {1}".format(first, last) middle, last) else: full_name =
we’ll do it in a way that breaks existing behavior.
return full_name.title() "{0} {1}".format(first,
def get_full_name(first, middle, last): last) return full_name.title() Running
Using the function """Return a full name."""
Save this as names.py
the test
full_name = "{0} {1} {2}".format(first, Now the test should pass again, which means our original
from full_names import get_full_name middle, last) return full_name.title() functionality is still intact.
.
janis = get_full_name('janis', 'joplin') Using the function ---------------------------------------
print(janis)
from full_names import get_full_name Ran 1 test in 0.000s
bob = get_full_name('bob', 'dylan')
O
C
print(bob) john = get_full_name('john', 'lee', 'hooker')
print(john) K
C
assertEqual(a, b) ...
assertNotEqual(a, b) ---------------------------------------
Ran 3 tests in 0.001s
Verify that x is True, or x is False In general you shouldn’t modify a test once it’s written.
When a test fails it usually means new code you’ve written
assertTrue(x) has broken existing functionality, and you need to modify OK
assertFalse(x) the new code until all existing tests pass.
If your original requirements have changed, it may be
Verify an item is in a list, or not in a list
appropriate to modify some tests. This usually happens in
assertIn(item, list) the early stages of a project when desired behavior is still
assertNotIn(item, list) being sorted out.
Pygame is a framework for making games using Python. Making games is fun, and it’s a great way to expand your programming skills and knowledge. Pygame takes care of
many of the lower-level tasks in building games, which lets you focus on the aspects of your game that make it interesting.
Pygame runs on all systems, but setup is slightly different The following code sets up an empty game window, and
on each OS. The instructions here assume you’re using starts an event loop and a loop that continually refreshes Useful rect attributes
Python 3, and provide a minimal installation of Pygame. If the screen. Once you have a rect object, there are a number of attributes that
are useful when positioning objects and detecting relative positions
these instructions don’t work for your system, see the more
detailed notes at http://ehmatthes.github.io/pcc/.
An empty game window of objects. (You can find more attributes in the Pygame
documentation.)
Pygame on Linux # Individual x and y values:
screen_rect.left, screen_rect.right
$ sudo apt-get install python3-dev
screen_rect.top, screen_rect.bottom
mercurial libsdl-image1.2-dev libsdl2-
screen_rect.centerx, screen_rect.centery
dev libsdl-ttf2.0-dev $ pip install
screen_rect.width, screen_rect.height
--user
hg+http://bitbucket.org/pygame/pygame
# Tuples
Pygame on OS X screen_rect.center
This assumes you’ve used Homebrew to install Python 3. screen_rect.size
$ brew install hg sdl sdl_image sdl_ttf Creating a rect object
$ pip install --user You can create a rect object from scratch. For example a small rect
hg+http://bitbucket.org/pygame/pygame object that’s filled in can represent a bullet in a game. The Rect()
class takes the coordinates of the upper left corner, and the width
Pygame on Windows and height of the rect. The draw.rect() function takes a screen
Find an installer at object, a color, and a rect. This function fills the given rect with the
https://bitbucket.org/pygame/pygame/downloads/ or given color.
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame that matches bullet_rect = pg.Rect(100, 100, 3, 15)
your version of Python. Run the installer file if it’s a .exe or .msi
color = (100, 100, 100)
file.
pg.draw.rect(screen, color, bullet_rect)
screen_center = screen_rect.center
C
Pygame watches for events such as key presses and Pygame
Pygame’shas a Group
event class which
loop registers makesany
an event working with a
time the You can detect when a single object collides with any
mouse actions. You can detect any event you care about in group of similar objects easier. A group is like a list,
mouse moves, or a mouse button is pressed or released. with member of a group. You can also detect when any member
Drawing
the an image
event loop, to the screen
and respond with any action that’s some extra functionality that’s helpful when building games. of one group collides with a member of another group.
Once an image is loaded and positioned, you can draw it to the
appropriate for your game. Responding to the mouse button
screen with the blit() method. The blit() method acts on the screen Making and filling a group Collisions between a single object and a group
for event in bepg.event.get(): if from Sprite. Removing an item from a group
Responding tothe
object, and takes key presses
image object and image rect as arguments. An object that will placed in a group must inherit The spritecollideany() function takes an object and a group, and
It’s important to delete elements that will never appear again in the
Pygame’s event.type == pg.MOUSEBUTTONDOWN: returns True if the object overlaps with any member of the group.
# Draw main
shipevent loop registers a KEYDOWN event any time a
to screen. from pygame.sprite import Sprite, Group game, so you don’t waste memory and resources.
key is pressed. When this happens, you can check for specific ship.fire_bullet()
screen.blit(ship, ship_rect) def if pg.sprite.spritecollideany(ship, aliens):
keys.
Finding the mouse position
Bullet(Sprite): ships_left -= 1
The blitme() method
for event in pg.event.get(): bullets.remove(bullet)
... position
The mouse defis returned as a tuple.
Game objects such as ships are often written as classes. Then a
if event.type == pg.KEYDOWN: draw_bullet(self): Collisions between two groups
blitme() method is usually defined, which draws the object to the
if event.key == pg.K_RIGHT: mouse_pos = pg.mouse.get_pos() The sprite.groupcollide() function takes two groups, and two
screen. ...
ship_rect.x += 1 booleans. The function returns a dictionary containing information
def blitme(self):
Clicking
defaupdate(self):
button about the members that have collided. The booleans tell Pygame
elif event.key == pg.K_LEFT: ...to know if the cursor is over an object such as a
You might want
"""Draw ship_rect.x
ship at current whether to delete the members of either group that have collided.
-= 1 location.""" button. The rect.collidepoint() method returns true when a point is
self.screen.blit(self.image,
elif event.key == pg.K_SPACE: self.rect) inside a rect=object. collisions =
bullets Group()
ship.fire_bullet() elif pg.sprite.groupcollide( bullets,
if button_rect.collidepoint(mouse_pos): aliens, True, True)
event.key == pg.K_q: new_bullet = Bullet()
start_game()
sys.exit() bullets.add(new_bullet)
Hiding the mouse score += len(collisions) * alien_point_value
Responding to released keys Looping through the items in a group
When the user releases a key, a KEYUP event is triggered. pg.mouse.set_visible(False) You can use text for a variety of purposes in a game. For
The sprites() method returns all the members of a group.
example you can share information with players, and you
if event.type == pg.KEYUP: for bullet in bullets.sprites(): can display a score. Displaying a message
if event.key == pg.K_RIGHT:
bullet.draw_bullet() The following code defines a message, then a color for the text and
ship.moving_right = False
the background color for the message. A font is defined using the
Calling update() on a group
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
Calling update() on a group automatically calls update() on each
associated with the image. We then center the image on the screen and display it. msg = "Play again?" msg_color = (100,
member of the group.
100, 100) bg_color = (230, 230, 230)
bullets.update()
f = pg.font.SysFont(None, 48)
msg_image = f.render(msg, True, msg_color,
The Pygame documentation is really helpful when building bg_color)
your own games. The home page for the Pygame project is msg_image_rect = msg_image.get_rect() at http://pygame.org/, and the home page for the msg_image_rect.center =
screen_rect.center documentation is at http://pygame.org/docs/. screen.blit(msg_image, msg_image_rect)
The most useful part of the documentation are the pages
about specific parts of Pygame, such as the Rect() class and the sprite module. You can find a list of these elements at the
top of the help pages.
plt.show()
Removing axes
matplotlib runs on all systems, but setup is slightly different Using a colormap You can customize or remove axes entirely. Here’s how to access
depending on your OS. If the minimal instructions here A colormap varies the point colors from one shade to another, each axis, and hide it.
don’t work for you, see the more detailed instructions at 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 plt.axes().get_xaxis().set_visible(False)
http://ehmatthes.github.io/pcc/. You should also consider
the cmap argument specifies which colormap to use. plt.axes().get_yaxis().set_visible(False)
installing the Anaconda distrubution of Python from
The edgecolor='none' argument removes the black outline
https://continuum.io/downloads/, which includes matplotlib. from each point.
Setting a custom figure size
You can make your plot as big or small as you want. Before
matplotlib on Linux plt.scatter(x_values, squares, c=squares, plotting your data, add the following code. The dpi argument is
cmap=plt.cm.Blues, edgecolor='none', optional; if you don’t know your system’s resolution you can omit
$ sudo apt-get install python3-matplotlib
s=10) the argument and adjust the figsize argument accordingly.
matplotlib on OS X plt.figure(dpi=128, figsize=(10, 6))
Start a terminal session and enter import matplotlib to see if
it’s already installed on your system. If not, try this command: Saving a plot
The matplotlib viewer has an interactive save button, but you can
$ pip install --user matplotlib also save your visualizations programmatically. To do so, replace
plt.show() with plt.savefig(). The bbox_inches='tight'
matplotlib on Windows argument trims extra whitespace from the plot.
You first need to install Visual Studio, which you can do from
https://dev.windows.com/. The Community edition is free. Then go plt.savefig('squares.png', bbox_inches='tight')
to https://pypi.python.org/pypi/matplotlib/ or
http://www.lfd.uic.edu/~gohlke/pythonlibs/#matplotlib and download
an appropriate installer file. C
The matplotlib gallery and documentation are at
http://matplotlib.org/. Be sure to visit the examples, gallery,
Making a line graph and pyplot links.
import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
squares = [0, 1, 4, 9, 16, 25]
Covers Python 3 and Python 2
plt.plot(x_values, squares)
plt.show()
You can make as many plots as you want on one figure. You can include as many individual graphs in one figure as
When you make multiple plots, you can emphasize Datetime formatting arguments
you want. This is useful, for example, when comparing
relationships in the data. For example you can fill the space The strftime() function generates a formatted string from a
datetime object, and the strptime() function genereates a
related datasets.
between two sets of data.
datetime object from a string. The following codes let you work with Sharing an x-axis
Plotting two sets of data dates exactly as you need to. The following code plots a set of squares and a set of cubes on
Here we use plt.scatter() twice to plot square numbers and %A Weekday name, such as Monday two separate graphs that share a common x-axis.
cubes on the same figure. The plt.subplots() function returns a figure object and a tuple
%B Month name, such as January
of axes. Each set of axes corresponds to a separate plot in the
import matplotlib.pyplot as plt %m Month, as a number (01 to 12) figure. The first two arguments control the number of rows and
%d Day of the month, as a number (01 to 31) columns generated in the figure.
x_values = list(range(11)) %Y Four-digit year, such as 2016 import matplotlib.pyplot as plt
squares = [x**2 for x in %y Two-digit year, such as 16
x_values] cubes = [x**3 for x in %H Hour, in 24-hour format (00 to 23) x_vals = list(range(11))
x_values] %I Hour, in 12-hour format (01 to 12) squares = [x**2 for x in
%p AM or PM x_vals] cubes = [x**3 for x in
plt.scatter(x_values, squares, c='blue', %M Minutes (00 to 59) x_vals]
edgecolor='none', s=20) plt.scatter(x_values, %S Seconds (00 to 61)
cubes, c='red', edgecolor='none', s=20) fig, axarr = plt.subplots(2, 1, sharex=True)
Converting a string to a datetime object
plt.axis([0, 11, 0, 1100]) new_years = dt.strptime('1/1/2017', '%m/%d/%Y') axarr[0].scatter(x_vals, squares)
plt.show() axarr[0].set_title('Squares')
Converting a datetime object to a string
Filling the space between data sets ny_string = dt.strftime(new_years, '%B %d, %Y')
The fill_between() method fills the space between two data axarr[1].scatter(x_vals, cubes, c='red')
print(ny_string) axarr[1].set_title('Cubes')
sets. It takes a series of x-values and two series of y-values. It also
takes a facecolor to use for the fill, and an optional alpha Plotting high temperatures
argument that controls the color’s transparency. The following code creates a list of dates and a corresponding list
plt.show()
plt.fill_between(x_values, cubes, squares, of high temperatures. It then plots the high temperatures, with the Sharing a y-axis
date labels displayed in a specific format. To share a y-axis, we use the sharey=True argument.
facecolor='blue', alpha=0.25)
outcomes = [1, 2, 3, 4, 5, 6]
To make a plot with Pygal, you specify the kind of plot and
frequencies = [18, 16, 18, 17, 18, 13]
then add the data.
Making a line graph chart = pygal.Bar()
To view the output, open the file squares.svg in a browser. chart.force_uri_protocol = 'http'
chart.x_labels = outcomes
import pygal chart.add('D6', frequencies)
chart.render_to_file('rolling_dice.svg')
x_values = [0, 1, 2, 3, 4, 5]
squares = [0, 1, 4, 9, 16, 25] Making a bar graph from a dictionary
Since each bar needs a label and a value, a dictionary is a great
way to store the data for a bar graph. The keys are used as the
chart = pygal.Line()
labels along the x-axis, and the values are used to determine the
chart.force_uri_protocol = 'http' The documentation for Pygal is available at
height of each bar.
chart.add('x^2', squares) http://www.pygal.org/.
import pygal
chart.render_to_file('squares.svg')
Adding labels and a title results = {
1:18, 2:16, 3:18, If you’re viewing svg output in a browser, Pygal needs to
--snip-- 4:17, 5:18, 6:13, render the output file in a specific way. The
chart = pygal.Line()
} force_uri_protocol attribute for chart objects needs to
chart.force_uri_protocol = 'http' chart = pygal.Bar()
chart.title = "Squares" be set to 'http'.
chart.force_uri_protocol = 'http'
chart.x_labels = x_values
chart.x_labels = results.keys() chart.add('D6',
chart.x_title = "Value"
chart.y_title = "Square of Value" results.values())
chart.add('x^2', squares) chart.render_to_file('rolling_dice.svg')
chart.render_to_file('squares.svg') Covers Python 3 and Python 2
chart = pygal.Line(style=chart_style)
--snip--
More cheat sheets available at
The data in a Django project is structured as a set of Users interact with a project through web pages, and a
models. project’s home page can start out as a simple page with no
data. A page usually needs a URL, a view, and a template.
Defining a model
To define the models for your app, modify the file models.py that Mapping a project’s URLs
was created in your app’s folder. The __str__() method tells The project’s main urls.py file tells Django where to find the urls.py
Django how to represent data objects based on this model. files associated with each app in the project.
from django.db import from django.conf.urls import include, url
Django is a web framework which helps you build models class from django.contrib import admin
Topic(models.Model):
interactive websites using Python. With Django you """A topic the user is learning about.""" urlpatterns = [
define the kind of data your site needs to work with, text = models.CharField(max_length=200) url(r'^admin/',
and you define the ways your users can work with date_added = include(admin.site.urls)), url(r'',
that data. models.DateTimeField( auto_now_add=
include('learning_logs.urls',
True)
namespace='learning_logs')), ]
def
__str__(self): Mapping an app’s URLs
It’s usualy best to install Django to a virtual environment, return self.text An app’s urls.py file tells Django which view to use for each URL in
where your project can be isolated from your other Python the app. You’ll need to make this file yourself, and save it in the
projects. Most commands assume you’re working in an
Activating a model app’s folder.
To use a model the app must be added to the tuple
active virtual environment. from django.conf.urls import url
INSTALLED_APPS, which is stored in the project’s settings.py file.
Create a virtual environment INSTALLED_APPS = ( from . import views
$ python –m venv ll_env --snip--
'django.contrib.staticfiles', urlpatterns = [
Activate the environment (Linux and OS X)
url(r'^$', views.index, name='index'),
$ source ll_env/bin/activate # My apps ]
'learning_logs',
Activate the environment (Windows) ) Writing a simple view
> ll_env\Scripts\activate A view takes information from a request and sends data to the
Migrating the database browser, often through a template. View functions are stored in an
Install Django to the active environment The database needs to be modified to store the kind of data that app’s views.py file. This simple view function doesn’t pull in any
the model represents. data, but it uses the template index.html to render the home page.
(ll_env)$ pip install Django
$ python manage.py makemigrations learning_logs from django.shortcuts import render
$ python manage.py migrate def
index(request):
Creating a superuser """The home page for Learning Log."""
To start a project we’ll create a new project, create a A superuser is a user account that has access to all aspects of the return render(request,
database, and start a development server. project.
'learning_logs/index.html')
Create a new project $ python manage.py createsuperuser
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>
{{ entry.date_added|date:'M d, Y H:i' }}
</p>
<p>
{{ entry.text|linebreaks }}
</p>
</li>
{% empty %}
<li>There are no entries yet.</li>
{% endfor %}
</ul>
{% endblock content %}
C
{% extends "learning_logs/base.html" %}
The register
There view of ways to create forms and work with
are a number The register template Restricting access to logged-in users
them.
The Youview
register can needs
use Django’s
to displaydefaults, or completely
a blank registration form when The{% block
register content
template %} the registration form in paragraph
displays Some pages are only relevant to registered users. The views for
customize
the your
page is first forms. For
requested, and a simple
then waycompleted
process to let users enter {% if form.errors %}
formats. these pages canCovers Python
be protected by3theand Python 2
@login_required decorator.
registration
data based forms. A successful
on your models,registration logs the user
use a ModelForm. in and
This creates <p>
{% extends 'learning_logs/base.html' %} Any view with this decorator will automatically redirect non-logged
redirects
a form to theallows
that home page.
users to enter data that will populate the Your username and password didn't match. in users to an appropriate page. Here’s an example views.py file.
fields django.contrib.auth
from on a model. import login from Please
{% block try again.
content %} from django.contrib.auth.decorators import /
django.contrib.auth
The register view on theimport
back ofauthenticate
this sheet shows a </p> login_required
from
simpledjango.contrib.auth.forms
approach to form processing. Ifimport
the view\doesn’t {% endif %} --snip--
<form method='post'
UserCreationForm
receive data from a form, it responds with a blank form. If it
action="{% url 'users:register' %}">
def
receives POST data from a form, it validates the data and <form method="post" @login_required def
register(request):
then saves it to the database. action="{% url 'users:login' topic(request, topic_id):
Users will
{% have data that belongs
csrf_token %} to them. Any model%}">
that should
"""Register a new user.""" if """Show a topic and all its entries."""
{%
be connected csrf token
directly
{{ form.as_p }} %}
to a user needs a field connecting instances
request.method != 'POST': # of the model to a specific user.
{{ form.as_p }} Setting the redirect URL
Show blank registration form.
form = UserCreationForm() else: Making <button name="submit">log in</button>
a topicname='submit'>register</button>
<button belong to a user The @login_required decorator sends unauthorized users to the
# Process completed form. <input
Only type='hidden'
the highest-level data in aname='next'
hierarchy needs to be directly login page. Add the following line to your project’s settings.py file
form = UserCreationForm( connected <input
value="{% type="hidden"
to a user. Tourl
do this import name="next"
the User model, and add
'learning_logs:index' it
%}"/> so Django will know how to find your login page.
data=request.POST) as a foreignvalue="{% url
key on the data 'learning_logs:index' %}"/>
model. LOGIN_URL = '/users/login/'
if After modifying the model you’ll need to migrate the database.
</form>
</form>
form.is_valid(): You’ll need to choose a user ID to connect each existing instance Preventing inadvertent access
new_user = form.save() to. Some pages serve data based on a parameter in the URL. You
{%{%endblock
endblockcontent
content%}%}
can check that the current user owns the requested data, and
# Log in, redirect to home page. from django.db import models return a 404 error if they don’t. Here’s an example view.
pw = request.POST['password1'] from django.contrib.auth.models import User
authenticated_user = authenticate( Iffrom
you provide some initial
django.http importdata,Http404
Django generates a form
class with the user’s existing data. Users can then modify and
username=new_user.username,
Topic(models.Model): save their data.
password=pw --snip-- def topic(request,
"""A topic the user is learning
) topic_id):
about.""" text = Creating a form with initial data
login(request, authenticated_user) models.CharField(max_length=200) """Show a topic and all its entries."""
The instance parameter allows you to specify initial data for a form.
return topic = Topics.objects.get(id=topic_id)
date_added = models.DateTimeField(
HttpResponseRedirect( reverse(' if topic.owner
form != request.user:
= EntryForm(instance=entry)
auto_now_add=True) owner =
learning_logs:index')) raise Http404
models.ForeignKey(User) Modifying data before saving
--snip--
def The argument commit=False allows you to make changes before
context = {'form': form} __str__(self):
return render(request, writing data to the database.
Heroku lets you push your project to a live server, making it return self.text
available to'users/register.html', context)
anyone with an internet connection. Heroku new_topic = form.save(commit=False)
offers a free service level, which lets you learn the Querying data for the current user new_topic.owner = request.user
deployment process without any commitment. You’ll need In a view, the request object has a user attribute. You can use this new_topic.save()
to install a set of heroku tools, and use git to track the state attribute to query for the user’s data. The filter() function then
pulls the data that belongs to the current user.
of your project. See http://devcenter.heroku.com/, and click The django-bootstrap3 app allows you to use the Bootstrap
on the Python link. topics = library to make your project look visually appealing. The app
Topic.objects.filter( owner=req provides tags that you can use in your templates to style
individual elements on a page. Learn more at http://django- uest.user) bootstrap3.readthedocs.io/.