Python Cheat Sheet
Python Cheat Sheet
msg = "Hello world!" Copying a list print("The alien's color is " + alien['color'])
print(msg) copy_of_bikes = bikes[:]
Adding a new key-value pair
Concatenation (combining strings)
alien['x_position'] = 0
first_name = 'albert'
last_name = 'einstein' Tuples are similar to lists, but the items in a tuple can't be Looping through all key-value pairs
full_name = first_name + ' ' + last_name modified.
print(full_name) fav_numbers = {'eric': 17, 'ever': 4} for
Making a tuple
name, number in fav_numbers.items():
dimensions = (1920, 1080) print(name + ' loves ' + str(number))
A simple if test C
if age >= 18: age = input("How old are you? ") age
print("You can vote!") = int(age)
C
def make_pizza(topping='bacon'):
"""Make a single-topping pizza."""
print("Have a " + topping + " pizza!") If you had infinite programming skills, what would you
build? Simple is better than complex
make_pizza()
As you're learning to program, it's helpful to think
make_pizza('pepperoni') If you have a choice between a simple and a complex
about the real-world projects you'd like to create. It's
solution, and both work, use the simple solution. Your
Returning a value a good habit to keep an "ideas" notebook that you
code will be easier to maintain, and it will be easier
can refer to whenever you want to start a new project.
for you and others to build on that code later on.
def add_numbers(x, y): If you haven't done so already, take a few minutes
"""Add two numbers and return the sum.""" and describe three projects you'd like to create.
return x + y
sum = add_numbers(3, 5)
print(sum)
newest_user = users[-1] C
Once you've defined a list, you can change individual elements
in the list. You do this by referring to the index of the item you want to modify.
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.
alue in a list upper_names = [] for name in names: When you're first learning about data structures such as
upper_names.append(name.upper()) lists, it helps to visualize how Python is working with the
17, 85, 1, 35, 82, 2, 77] information in your program. pythontutor.com is a great tool
) for seeing how Python keeps track of the information in a
Using a comprehension to convert a list of names to list. Try running the following code on pythontutor.com, and
value upper case then run your own code.
Build a list and print the items in the list
17, 85, 1, 35, 82, 2, 77] names = ['kai', 'abe', 'ada', 'gus', 'zoe']
You can modify the value associated with any key in a alien_0 = {'color': 'green', 'points': 5} # Store people's favorite languages.
dictionary. To do so give the name of the dictionary and fav_languages = { 'jen':
enclose the key in square brackets, then provide the new alien_0['x'] = 0 'python',
value for that key. alien_0['y'] = 25 'sarah': 'c',
alien_0['speed'] = 1.5 'edward': 'ruby',
Modifying values in a dictionary 'phil': 'python',
Adding to an empty dictionary }
alien_0 = {'color': 'green', 'points': 5}
print(alien_0) alien_0 = {} # Show each person's favorite language. for
alien_0['color'] = 'green' name, language in fav_languages.items():
# Change the alien's color and point value. alien_0['points'] = 5 print(name + ": " + language)
alien_0['color'] = 'yellow'
alien_0['points'] = 10 print(alien_0) Looping through all the keys
To access the value associated with an individual key give # Show everyone who's taken the survey. for
the name of the dictionary and then place the key in a set of name in fav_languages.keys():
square brackets. If the key you're asking for is not in the print(name)
You can remove any key-value pair you want from a dictionary, an error will occur.
dictionary. To do so use the del keyword and the dictionary You can also use the get() method, which returns None Looping through all the values
name, followed by the key in square brackets. This will instead of an error if the key doesn't exist. You can also
delete the key and its associated value. specify a default value to use if the key is not in the # Show all the languages that have been chosen.
dictionary. for language in fav_languages.values():
Deleting a key-value pair
Getting the value associated with a key print(language)
alien_0 = {'color': 'green', 'points': 5}
print(alien_0) alien_0 = {'color': 'green', 'points': 5} Looping through all the keys in order
You can find the number of key-value pairs in a dictionary. alien_0 = {'color': 'green'}
Finding a dictionary's length alien_color = alien_0.get('color')
alien_points = alien_0.get('points', 0)
num_responses = len(fav_languages)
print(alien_color)
print(alien_points)
C
overs Python 3 and Python 2
users = { # Store multiple languages for each person. # Make a million green aliens, worth 5 points
'aeinstein': { fav_languages = { # each. Have them all start in one row.
'first': 'albert', 'jen': ['python', 'ruby'], for alien_num in range(1000000):
'sarah': ['c'], new_alien = {}
'last': 'einstein',
'edward': ['ruby', 'go'], new_alien['color'] = 'green'
'location': 'princeton',
new_alien['points'] = 5 new_alien['x']
}, 'phil': ['python', 'haskell'],
= 20 * alien_num new_alien['y'] = 0
'mcurie': { }
aliens.append(new_alien)
'first': 'marie',
'last': 'curie', # Show all responses for each person. # Prove the list contains a million aliens.
'location': 'paris', for name, langs in
num_aliens = len(aliens)
}, fav_languages.items(): print(name +
": ") for lang in langs:
} for username, user_dict in print("Number of aliens created:")
print("- " + lang)
users.items(): print("\nUsername: " print(num_aliens)
+ username) full_name = nesting items much deeper than what you see here there
user_dict['first'] + " " full_name are probably simpler ways of managing your data, such as
+= user_dict['last'] location = using classes.
user_dict['location']
Testing numerical values is similar to testing string values. Several kinds of if statements exist. Your choice of which to
use depends on the number of conditions you need to test.
Testing equality and inequality You can have as many elif blocks as you need, and the
else block is always optional.
>>> age = 18
>>> age == 18 Simple if statement
True
>>> age != 18 age = 19
False if age >= 18: print("You're old
enough to vote!")
Comparison operators
While loops run as long as certain conditions remain You can check multiple conditions at the same time. The
true. You can use while loops to let your programs and operator returns True if all the conditions listed are
run as long as your users want them to. True. The or operator returns True if any condition is True.
prompt = "\nTell me something, and I'll " Removing all cats from a list of pets
current_number = 1
while current_number <= prompt += "repeat it back to you." pets = ['dog', 'cat', 'dog', 'fish', 'cat',
5: prompt += "\nEnter 'quit' to end the program. " 'rabbit', 'cat'] print(pets) while 'cat' in
print(current_number) active = True while pets: pets.remove('cat') print(pets)
Sublime Text doesn't run programs that prompt the user for active: message =
current_number += 1
input. You can use Sublime Text to write programs that input(prompt)
prompt for input, but you'll need to run these programs from if message ==
a terminal. 'quit': active =
False else:
You can use the break statement and the continue statement
print(message)
with any of Python's loops. For example you can use break to
quit a for loop that's working through a list or a dictionary. You
can use continue to skip over certain items when looping
through a list or dictionary as well. Using break to exit a loop
prompt = "\nWhat cities have you visited?"
prompt += "\nEnter 'quit' when you're done. "
while True: city = input(prompt)
if city == 'quit': break else:
print("I've been to " + city + "!")
C
The two main kinds of arguments are positional and A function can return a value or a set of values. When a
keyword arguments. When you use positional arguments function returns a value, the calling line must provide a
Python matches the first argument in the function call with variable in which to store the return value. A function stops
the first parameter in the function definition, and so forth. running when it reaches a return statement.
With keyword arguments, you specify which parameter
each argument should be assigned to in the function call. Returning a single value
When you use keyword arguments, the order of the
arguments doesn't matter. def get_full_name(first, last):
"""Return a neatly formatted full
Using positional arguments name.""" full_name = first + ' ' + last
Functions are named blocks of code designed to do return full_name.title()
one specific job. Functions allow you to write code def describe_pet(animal, name):
once that can then be run whenever you need to """Display information about a pet.""" musician = get_full_name('jimi', 'hendrix')
print("\nI have a " + animal + ".") print(musician)
accomplish the same task. Functions can take in the
print("Its name is " + name + ".")
information they need, and return the information they
Returning a dictionary
generate. Using functions effectively makes your describe_pet('hamster', 'harry')
programs easier to write, read, test, and fix. describe_pet('dog', 'willie') def build_person(first, last):
"""Return a dictionary of information
Using keyword arguments about a person.
The first line of a function is its definition, marked by the """
keyword def. The name of the function is followed by a set def describe_pet(animal, name): person = {'first': first, 'last': last}
of parentheses and a colon. A docstring, in triple quotes, """Display information about a pet.""" return person
describes what the function does. The body of a function is print("\nI have a " + animal + ".")
indented one level. print("Its name is " + name + ".") musician = build_person('jimi', 'hendrix')
To call a function, give the name of the function followed print(musician)
by a set of parentheses. describe_pet(animal='hamster', name='harry')
describe_pet(name='willie', animal='dog') Returning a dictionary with optional values
Making a function
def greet_user(): def build_person(first, last, age=None):
"""Display a simple greeting.""" """Return a dictionary of information about
print("Hello!") a person.
You can provide a default value for a parameter. When """ person = {'first': first,
function calls omit this argument the default value will be 'last': last} if age:
greet_user() used. Parameters with default values must be listed after person['age'] = age return person
parameters without default values in the function's definition
so positional arguments can still work correctly. musician = build_person('jimi', 'hendrix', 27)
print(musician)
Using a default value
musician = build_person('janis', 'joplin')
print(musician)
C
You can pass a list as an argument to a function, and the
function can work with the values in the list. Any changes
the function makes to the list will affect the original list. You
can prevent a function from modifying a list by passing a
copy of the list as an argument.
def greet_users(names):
"""Print a simple greeting to
everyone.""" for name in names:
msg = "Hello, " + name + "!"
print(msg)
print("\nUnprinted:", unprinted)
print("Printed:", printed)
print_models(original[:], printed)
print("\nOriginal:", original)
print("Printed:", printed)
C
You can store your functions in a separate file called a
module, and then import the functions you need into the file
containing your main program. This allows for cleaner
program files. (Make sure your module is stored in the
same directory as your main program.)
Storing a function in a module
File: pizza.py
def make_pizza(size, *toppings):
"""Make a pizza."""
print("\nMaking a " + size + "
pizza.") print("Toppings:") for
topping in toppings: print("- " +
topping)
Importing an entire module
File: making_pizzas.py
Every function in the module is available in the program file.
import pizza
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')
C
from pizza import make_pizza As you can see there are many ways to write and call a
Sometimes you won't know how many arguments a function function. When you're starting out, aim for something
will need to accept. Python allows you to collect an arbitrary make_pizza('medium', 'pepperoni') that simply works. As you gain experience you'll
number of arguments into one parameter using the * make_pizza('small', 'bacon', 'pineapple') develop an understanding of the more subtle
operator. A parameter that accepts an arbitrary number of advantages of different structures such as positional
arguments must come last in the function definition.
Giving a module an alias and keyword arguments, and the various approaches
The ** operator allows a parameter to collect an arbitrary import pizza as p to importing functions. For now if your functions do
number of keyword arguments. what you need them to, you're doing well.
p.make_pizza('medium', 'pepperoni')
Collecting an arbitrary number of arguments
p.make_pizza('small', 'bacon', 'pineapple')
def make_pizza(size, *toppings): Giving a function an alias
"""Make a pizza.""" from
You can pizza
modify import make_pizza
an attribute's as mpor you can
value directly,
print("\nMaking a " + size + " write methods that manage updating values more carefully.
pizza.") print("Toppings:") for mp('medium', 'pepperoni') mp('small',
topping in toppings: print("- " + Modifying
'bacon',an'pineapple')
attribute directly
topping)
Importing all
my_new_car = functions
Car('audi', from'a4',
a module
2016)
# Make three pizzas with different toppings. my_new_car.fuel_level = 5 you see it in others' code. It can
Don't do this, but recognize it when
make_pizza('small', 'pepperoni') result in naming conflicts, which can cause errors.
make_pizza('large', 'bacon bits', 'pineapple') Writing
from apizza
method import *
to update an attribute's value
make_pizza('medium', 'mushrooms', 'peppers',
'onions', 'extra cheese') make_pizza('medium', 'pepperoni')
def update_fuel_level(self, new_level):
make_pizza('small',
"""Update the fuel level."""'bacon', 'pineapple')
if
Collecting an arbitrary number of keyword arguments new_level <= self.fuel_capacity:
self.fuel_level = new_level else:
def build_profile(first, last, **user_info): print("The tank can't hold that much!")
"""Build a user's profile dictionary."""
# Build a dict with the required keys.
profile = {'first': first, 'last': last}
Writing a method to increment an attribute's value
# Add any other keys and values.
for key, value in user_info.items(): def add_fuel(self, amount): """Add fuel to
profile[key] = value the tank.""" if (self.fuel_level + amount
<= self.fuel_capacity):
return profile self.fuel_level += amount print("Added
fuel.") else: print("The tank
# Create two users with different kinds won't hold that much.")
# 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)
class ElectricCar(Car):
--snip-- def
charge(self):
"""Fully charge the vehicle."""
self.charge_level = 100
print("The vehicle is fully charged.")
my_ecar.charge()
my_ecar.drive()
C
Consider how we might model a car. What information Creating an object from a class
would we associate with a car, and what behavior would it
have? The information is stored in variables called my_car = Car('audi', 'a4', 2016)
attributes, and the behavior is represented by functions.
Functions that are part of a class are called methods. Accessing attribute values
The Car class print(my_car.make)
print(my_car.model)
class Car(): print(my_car.year)
"""A simple attempt to model a car."""
def __init__(self, make, model,
Calling methods
year): """Initialize car my_car.fill_tank()
attributes.""" self.make = make my_car.drive()
self.model = model self.year =
year Creating multiple objects
# Fuel capacity and level in gallons. my_car = Car('audi', 'a4', 2016)
self.fuel_capacity = 15 self.fuel_level my_old_car = Car('subaru', 'outback', 2013)
= 0 my_truck = Car('toyota', '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.
C
Overriding parent methods
class ElectricCar(Car):
--snip-- def
fill_tank(self):
"""Display an error message."""
print("This car has no fuel tank!")
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()
C
Importing all classes from a module
(Don’t do this, but recognize it when you see it.)
from car import *
A class can have objects as attributes. This allows classes
Classes should inherit from object
to work together to model complex situations. my_beetle = Car('volkswagen', 'beetle', 2016)
class ClassName(object):
A Battery class
The Car class in Python 2.7
class Battery():
"""A battery for an electric car.""" class Car(object):
def __init__(self,
size=70): A list can hold as many items as you want, so you can Child class __init__() method is different
"""Initialize battery attributes.""" make a large number of objects from a class and store
them in a list. class ChildClassName(ParentClass):
# Capacity in kWh, charge level in %.
Here's an example showing how to make a fleet of rental def __init__(self):
self.size = size self.charge_level =
0 cars, and make sure all the cars are ready to drive. super(ClassName, self).__init__()
def A fleet of rental cars The ElectricCar class in Python 2.7
get_range(self):
"""Return the battery's range.""" class ElectricCar(Car): def
from car import Car, ElectricCar
if self.size == 70: __init__(self, make, model, year):
return 240 super(ElectricCar, self).__init__(
elif self.size == 85: # Make lists to hold a fleet of
cars. gas_fleet = [] electric_fleet make, model, year)
return 270
= [] More cheat sheets available at
Using an instance as an attribute
# Make 500 gas cars and 250 electric cars.
for _ in range(500): car = Car('ford',
class ElectricCar(Car):
'focus', 2016) gas_fleet.append(car) for
--snip-- _ in range(250): ecar =
def __init__(self, make, model, ElectricCar('nissan', 'leaf', 2016)
year): """Initialize an electric electric_fleet.append(ecar)
car.""" super().__init__(make,
model, year) # Fill the gas cars, and charge electric
cars. for car in gas_fleet:
# Attribute specific to electric cars. car.fill_tank() for ecar in electric_fleet:
self.battery = Battery() ecar.charge()
def
charge(self): print("Gas cars:", len(gas_fleet))
"""Fully charge the vehicle.""" print("Electric cars:", len(electric_fleet))
self.battery.charge_level = 100
print("The vehicle is fully charged.")
my_ecar.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()
Storing the lines in a list Opening a file using an absolute path
filename = 'siddhartha.txt' f_path = "/home/ehmatthes/books/alice.txt"
with open(filename) as with open(f_path) as f_obj:
f_obj: lines = lines = f_obj.readlines()
f_obj.readlines()
for line in lines:
print(line.rstrip()) Opening a file on Windows
Windows will sometimes interpret forward slashes incorrectly. If
you run into this, use backslashes in your file paths.
f_path = "C:\Users\ehmatthes\books\alice.txt"
Your programs can read information in from files, and
with open(f_path) as f_obj: lines =
they can write data to files. Reading from files allows
f_obj.readlines()
you to work with a wide variety of information; writing Passing the 'w' argument to open() tells Python you want to
to files allows users to pick up where they left off the write to the file. Be careful; this will erase the contents of
next time they run your program. You can write text to the file if it already exists. Passing the 'a' argument tells
files, and you can store Python structures such as Python you want to append to the end of an existing file.
lists in data files. Writing to an empty file When you think an error may occur, you can write a
tryexcept block to handle the exception that might be raised.
Exceptions are special objects that help your filename = 'programming.txt' The try block tells Python to try running some code, and the
programs respond to errors in appropriate ways. For with open(filename, 'w') as except block tells Python what to do if the code results in a
example if your program tries to open a file that f: particular kind of error.
doesn’t exist, you can use exceptions to display an f.write("I love programming!")
Handling the ZeroDivisionError exception
informative error message instead of having the
Writing multiple lines to an empty file try: print(5/0) except
program crash. ZeroDivisionError: print("You
filename = 'programming.txt' can't divide by zero!")
with open(filename, 'w') as
f: Handling the FileNotFoundError exception
f.write("I love programming!\n")
To read from a file your program needs to open the file and f_name = 'siddhartha.txt' try: with
f.write("I love creating new games.\n")
then read the contents of the file. You can read the entire open(f_name) as f_obj: lines =
contents of the file at once, or read the file line by line. The f_obj.readlines() except FileNotFoundError:
Appending to a file
with statement makes sure the file is closed properly when msg = "Can't find file {0}.".format(f_name)
the program has finished accessing the file. print(msg)
filename = 'programming.txt'
Reading an entire file at once with open(filename, 'a') as
f:
f.write("I also love working with data.\n")
f.write("I love making apps as well.\n")
C
filename = 'siddhartha.txt'
with open(filename) as
f_obj: contents = When Python runs the open() function, it looks for the file in
f_obj.read() the same directory where the program that's being excuted It can be hard to know what kind of exception to handle
is stored. You can open a file from a subfolder using a when writing code. Try writing your code without a try block,
print(contents) relative path. You can also use an absolute path to open and make it generate an error. The traceback will tell you
any file on your system. what kind of exception your program needs to handle.
Reading line by line
Each line that's read from the file has a newline character at the
end of the line, and the print function adds its own newline
character. The rstrip() method gets rid of the the extra blank lines
this would result in when printing to the terminal. overs Python 3 and Python 2
filename = 'siddhartha.txt'
with open(filename) as
Opening a file from a subfolder
f_obj: for line in
f_obj:
print(line.rstrip())
f_path = "text_files/alice.txt"
with open(f_path) as f_obj:
lines = f_obj.readlines()
for line in lines:
print(line.rstrip())
Well-written, properly tested code is not very prone to
The try block should only contain code that may cause an internal errors such as syntax or logical errors. But every
error. Any code that depends on the try block running Sometimes you want your program to just continue running time your program depends on something external such as
successfully should be placed in the else block. when it encounters an error, without reporting the error to user input or the existence of a file, there's a possibility of
the user. Using the pass statement in an else block allows an exception being raised.
Using an else block you to do this.
It's up to you how to communicate errors to your users.
print("Enter two numbers. I'll divide them.") Using the pass statement in an else block Sometimes users need to know if a file is missing;
sometimes it's better to handle the error silently. A little
x = input("First number: ") y f_names = ['alice.txt', 'siddhartha.txt', experience will help you know how much to report.
= input("Second number: ") 'moby_dick.txt', 'little_women.txt']
try: result = int(x) / int(y) for f_name in
except ZeroDivisionError: f_names:
print("You can't divide by zero!") # Report the length of each file found.
else: print(result) try: with open(f_name) as f_obj:
lines = f_obj.readlines() except
FileNotFoundError:
# Just move on to the next
file. pass else:
Preventing crashes from user input num_lines = len(lines)
Without the except block in the following example, the program msg = "{0} has {1}
would crash if the user tries to divide by zero. As written, it will lines.".format( f_name,
handle the error gracefully and keep running. num_lines) print(msg)
C
"""Store some numbers."""
import json
import json
print(numbers)
import json
f_name = 'numbers.json'
try: with open(f_name) as f_obj:
numbers = json.load(f_obj) except
FileNotFoundError: msg = "Can’t find
{0}.".format(f_name) print(msg) else:
print(numbers)
C
When you write a function or a class, you can also Building a testcase with one unit test
write tests for that code. Testing proves that your To build a test case, make a class that inherits from
code works as it's supposed to in the situations it's unittest.TestCase and write methods that begin with test_.
Save this as test_full_names.py
designed to handle, and also when people use your
programs in unexpected ways. Writing tests gives import unittest
you confidence that your code will work correctly as from full_names import get_full_name
more people begin to use your programs. You can class
also add new features to your programs and know NamesTestCase(unittest.TestCase):
that you haven't broken existing behavior. """Tests for names.py."""
def
A unit test verifies that one specific aspect of your test_first_last(self):
"""Test names like Janis Joplin."""
code works as it's supposed to. A test case is a full_name = get_full_name('janis',
collection of unit tests which verify your code's 'joplin')
behavior in a wide variety of situations. self.assertEqual(full_name,
'Janis Joplin')
unittest.main()
Running the test
Python reports on each unit test in the test case. The dot reports a
single passing test. Python informs us that it ran 1 test in less than
0.001 seconds, and the OK lets us know that all unit tests in the
test case passed.
.
---------------------------------------
Ran 1 test in 0.000s
A function to test Failing tests are important; they tell you that a change in the
Save this as full_names.py code has affected existing behavior. When a test fails, you
need to modify the code so the existing behavior still works.
def get_full_name(first, last):
"""Return a full name.""" Modifying the function
full_name = "{0} {1}".format(first, last) We’ll modify get_full_name() so it handles middle names, but
return full_name.title() we’ll do it in a way that breaks existing behavior.
O
K
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)
Fixing the code
When a test fails, the code needs to be modified until the test
passes again. (Don’t make the mistake of rewriting your tests to
fit your new code.) Here we can make the middle name optional.
def get_full_name(first, last, middle=''):
"""Return a full name.""" if middle:
full_name = "{0} {1} {2}".format(first,
middle, last) else: full_name =
"{0} {1}".format(first,
last) return full_name.title() Running the
test
Now the test should pass again, which means our original
functionality is still intact.
.
--------------------------------------- C
You can add as many unit tests to a test case as you need. Testing a class is similar to testing a function, since you’ll When testing a class, you usually have to make an instance
To write a new test, add a new method to your test case mostly be testing your methods. of the class. The setUp() method is run before every test.
class. Any instances you make in setUp() are available in every
A class to test test you write.
Testing middle names Save as accountant.py
We’ve shown that get_full_name() works for first and last Using setUp() to support multiple tests
names. Let’s test that it works for middle names as well. class Accountant(): The instance self.acc can be used in each new test.
"""Manage a bank account.""" import unittest
import unittest def __init__(self, from accountant import Accountant class
from full_names import get_full_name balance=0): TestAccountant(unittest.TestCase):
class self.balance = balance """Tests for the class Accountant."""
NamesTestCase(unittest.TestCase): def deposit(self, def setUp(self):
"""Tests for names.py.""" amount): self.balance self.acc = Accountant()
def += amount def test_initial_balance(self):
test_first_last(self): def withdraw(self, # Default balance should be 0.
"""Test names like Janis Joplin.""" amount): self.balance - self.assertEqual(self.acc.balance, 0)
full_name = get_full_name('janis', = amount # Test non-default balance.
'joplin') acc = Accountant(100)
self.assertEqual(full_name, Building a testcase self.assertEqual(acc.balance, 100)
'Janis Joplin') For the first test, we’ll make sure we can start out with different def
def initial balances. Save this as test_accountant.py. test_deposit(self): #
test_middle(self): Test single deposit.
"""Test names like David Lee Roth.""" import unittest self.acc.deposit(100)
full_name = get_full_name('david', from accountant import Accountant self.assertEqual(self.acc.balance, 100)
'roth', 'lee') class
self.assertEqual(full_name, TestAccountant(unittest.TestCase): # Test multiple deposits.
'David Lee Roth') """Tests for the class Accountant."""
self.acc.deposit(100)
def
self.acc.deposit(100)
unittest.main() test_initial_balance(self): #
self.assertEqual(self.acc.balance, 300)
Default balance should be 0.
Running the tests def
acc = Accountant()
test_withdrawal(self): #
The two dots represent two passing tests. self.assertEqual(acc.balance, 0)
Test single withdrawal.
self.acc.deposit(1000)
.. # Test non-default balance. self.acc.withdraw(100)
--------------------------------------- acc = Accountant(100) self.assertEqual(self.acc.balance, 900)
Ran 2 tests in 0.000s self.assertEqual(acc.balance, 100)
unittest.main()
unittest.main()
OK
.
Python provides a number of assert methods you can use --------------------------------------- Running the tests
to test your code. Ran 1 test in 0.000s
Verify that a==b, or a != b
OK
> python –m pip install --user pygame- Setting a custom window size
1.9.2a0-cp35-none-win32.whl The display.set_mode() function accepts a tuple that defines the
screen size. Many objects in a game are images that are moved around
Testing your installation the screen. It’s easiest to use bitmap (.bmp) image files, but
screen_dim = (1200, 800)
To test your installation, open a terminal session and try to import you can also configure your system to work with jpg, png,
screen = pg.display.set_mode(screen_dim)
Pygame. If you don’t get any error messages, your installation was and gif files as well.
successful.
Setting a custom background color Loading an image
$ python Colors are defined as a tuple of red, green, and blue values. Each
>>> import pygame value ranges from 0-255. ship = pg.image.load('images/ship.bmp')
>>>
bg_color = (230, 230, 230)
Getting the rect object from an image
screen.fill(bg_color)
ship_rect = ship.get_rect()
Positioning an image
Many objects in a game can be treated as simple With rects, it’s easy to position an image wherever you want on the
screen, or in relation to another object. The following code positions
rectangles, rather than their actual shape. This simplifies
a ship object at the bottom center of the screen.
code without noticeably affecting game play. Pygame has a
rect object that makes it easy to work with game objects. ship_rect.midbottom = screen_rect.midbottom
screen_center = screen_rect.center
Pygame watches for events such as key presses and
mouse actions. You can detect any event you care about in
the event loop, and respond with any action that’s
appropriate for your game.
Responding to key presses Pygame’s event loop registers an event any time the
Pygame’s main event loop registers a KEYDOWN event any time a
mouse moves, or a mouse button is pressed or released.
key is pressed. When this happens, you can check for specific
keys. Responding to the mouse button
for event in pg.event.get(): if
for event in pg.event.get(): if
event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT: event.type == pg.MOUSEBUTTONDOWN:
You can detectship_rect.x
when a single object +=collides
1 with any ship.fire_bullet()
member
elif of a group.
event.key ==You can also detect when any member
pg.K_LEFT:
of one group collides with a member
ship_rect.x -= 1 of another group. Finding the mouse position
elif event.key == pg.K_SPACE: The mouse position is returned as a tuple.
Collisions between a single object and a group
ship.fire_bullet() elif
The spritecollideany() function takes an object and a group, and mouse_pos = pg.mouse.get_pos()
event.key == pg.K_q:
returns True if the object overlaps with any member of the group.
sys.exit()
if pg.sprite.spritecollideany(ship, aliens): Clicking a button
Responding to released You might want to know if the cursor is over an object such as a
ships_left -= 1 keys
When the user releases a key, a KEYUP event is triggered. button. The rect.collidepoint() method returns true when a point is
inside a rect object.
Collisions between two groups
if event.type == pg.KEYUP:
The sprite.groupcollide() function takes two groups, and two if button_rect.collidepoint(mouse_pos):
if event.key
booleans. == pg.K_RIGHT:
The function returns a dictionary containing information start_game()
ship.moving_right = False
about the members that have collided. The booleans tell Pygame
whether to delete the members of either group that have collided.
Hiding the mouse
collisions = pg.sprite.groupcollide(
bullets, aliens, True, True) pg.mouse.set_visible(False)
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.
Using a colormap
matplotlib runs on all systems, but setup is slightly different A colormap varies the point colors from one shade to another, Removing axes
depending on your OS. If the minimal instructions here based on a certain value for each point. The value used to You can customize or remove axes entirely. Here’s how to access
determine the color of each point is passed to the c argument, and each axis, and hide it.
don’t work for you, see the more detailed instructions at the cmap argument specifies which colormap to use.
http://ehmatthes.github.io/pcc/. You should also consider The edgecolor='none' argument removes the black outline plt.axes().get_xaxis().set_visible(False)
installing the Anaconda distrubution of Python from from each point. plt.axes().get_yaxis().set_visible(False)
https://continuum.io/downloads/, which includes matplotlib.
plt.scatter(x_values, squares, c=squares, Setting a custom figure size
matplotlib on Linux cmap=plt.cm.Blues, edgecolor='none', You can make your plot as big or small as you want. Before plotting
s=10) your data, add the following code. The dpi argument is optional; if
$ sudo apt-get install python3-matplotlib you don’t know your system’s resolution you can omit 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 plt.savefig('squares.png', bbox_inches='tight')
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.
The matplotlib gallery and documentation are at
http://matplotlib.org/. Be sure to visit the examples, gallery,
and pyplot links.
Making a line graph
Covers Python 3 and Python 2
import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
squares = [0, 1, 4, 9, 16, 25]
plt.plot(x_values, squares)
plt.show()
new_years = dt(2017, 1, 1)
fall_equinox = dt(year=2016, month=9, day=22)
Making a scatter plot You can add as much data as you want when making a
Data visualization involves exploring data through
The data for a scatter plot needs to be a list containing tuples of visualization.
visual representations. Pygal helps you make visually
the form (x, y). The stroke=False argument tells Pygal to make Plotting squares and cubes
appealing representations of the data you’re working
an XY chart with no line connecting the points.
with. Pygal is particularly well suited for visualizations
that will be presented online, because it supports
interactive elements.
squares = [(x, x**2) for x in range(1000)] Filling the area under a data series
Pygal allows you to fill the area under or over each series of data.
To make a plot with Pygal, you specify the kind of plot and The default is to fill from the x-axis up, but you can fill from any
Making a bar graph
then add the data. horizontal line using the zero argument.
A bar graph requires a list of values for the bar sizes. To label the
Making a line graph bars, pass a list of the same length to x_labels.
chart = pygal.Line(fill=True, zero=0)
To view the output, open the file squares.svg in a browser. import pygal
import pygal
outcomes = [1, 2, 3, 4, 5, 6]
frequencies = [18, 16, 18, 17, 18, 13]
x_values = [0, 1, 2, 3, 4, 5]
squares = [0, 1, 4, 9, 16, 25]
chart = pygal.Bar()
chart.force_uri_protocol = 'http'
chart = pygal.Line()
chart.x_labels = outcomes chart.add('D6',
chart.force_uri_protocol = 'http'
frequencies)
chart.add('x^2', squares) chart.render_to_file('rolling_dice.svg')
chart.render_to_file('squares.svg')
Making a bar graph from a dictionary
Adding labels and a title 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 The documentation for Pygal is available at
labels along the x-axis, and the values are used to determine the
http://www.pygal.org/.
height of each bar.
wm = World()
wm.force_uri_protocol = 'http'
wm.title = 'North America'
wm.add('North America', ['ca', 'mx', 'us'])
wm.render_to_file('north_america.svg')
populations = {
'ca': 34126000,
'us': 309349000,
'mx': 113423000,
}
wm = World()
wm.force_uri_protocol = 'http' wm.title
= 'Population of North America'
wm.add('North America', populations)
wm.render_to_file('na_populations.svg')
Configuration settings
Some settings are controlled by a Config object.
Pygal lets you customize many elements of a plot. There
are some excellent default themes, and many options for my_config = pygal.Config()
styling individual plot elements. my_config.show_y_guides = False
Using built-in styles my_config.width = 1000
To use built-in styles, import the style and make an instance of my_config.dots_size = 5
the style class. Then pass the style object with the style
argument when you make the chart object. chart = pygal.Line(config=my_config) --snip-
-
import pygal
from pygal.style import LightGreenStyle
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.
Registering a model
You can register your models with Django’s admin site, which
makes it easier to work with the data in your project. To do this,
modify the app’s admin.py file. View the admin site at
http://localhost:8000/admin/.
admin.site.register(Topic)
{% extends 'learning_logs/base.html' %}
{% block content %}
{% endblock content %}
{% endblock content %}
Users will have data that belongs to them. Any model that should If you provide some initial data, Django generates a form
The register view The registerdirectly
template Restricting access to logged-in users
be connected to a user needs a field connecting instances with the user’s existing data. Users can then modify and
The register view needs to display a blank registration form when The
of register
the model template displays
to a specific user. the registration form in paragraph Some pages are only relevant to registered users. The views for
the page is first requested, and then process completed registration formats. save their data.
these pages can be protected by the @login_required decorator.
forms. A successful registration logs the user in and redirects to the Making a topic belong to a user Any view with
Creating this decorator
a form will automatically
with initial data redirect non-logged
home page. {% extends 'learning_logs/base.html' %} in users to an appropriate page. Here’s an example views.py file.
Only the highest-level data in a hierarchy needs to be directly The instance parameter allows you to specify initial data for a form.
connected to a user. To do this import the User model, and add it
from django.contrib.auth import login from {%a foreign
block key
content %} model. from django.contrib.auth.decorators import /
as on the data
django.contrib.auth import authenticate from login_required
form = EntryForm(instance=entry)
After modifying the model you’ll need to migrate the database.
django.contrib.auth.forms import \ --snip--
You’ll need to
<form choose a user ID to connect each existing instance
method='post'
UserCreationForm Modifying data before saving
to. action="{% url 'users:register' %}">
def @login_required def allows you to make changes before
The argument commit=False
register(request): from django.db import models topic(request,
writing topic_id):
data to the database.
"""Register a new user.""" if {% csrf_token %} """Show a topic and all its entries."""
from django.contrib.auth.models import User
request.method != 'POST': # {{ form.as_p }} new_topic = form.save(commit=False)
class
Show blank registration form. Topic(models.Model): Setting the redirect=URL
new_topic.owner request.user
form = UserCreationForm() else: <button name='submit'>register</button>
"""A topic the user is learning The @login_required decorator sends unauthorized users to the
new_topic.save()
# Process completed form. <input type='hidden'
about.""" text = name='next' login page. Add the following line to your project’s settings.py file
form = UserCreationForm( value="{% url 'learning_logs:index' %}"/> so Django will know how to find your login page.
models.CharField(max_length=200)
data=request.POST) date_added = models.DateTimeField( LOGIN_URL = '/users/login/'
if </form>
auto_now_add=True) owner =
form.is_valid(): models.ForeignKey(User) Preventing inadvertent access
new_user = form.save() def%}
{% endblock content Some pages serve data based on a parameter in the URL. You
# Log in, redirect to home page. __str__(self): can check that the current user owns the requested data, and
pw = request.POST['password1'] return a 404 error if they don’t. Here’s an example view.
return self.text
authenticated_user = authenticate(
username=new_user.username, from django.http import Http404
Querying data for the current user
password=pw In a view, the request object has a user attribute. You can use this
) attribute to query for the user’s data. The filter() function then
--snip-- def topic(request,
login(request, authenticated_user) pulls the data that belongs to the current user. topic_id):
return HttpResponseRedirect( """Show a topic and all its entries."""
reverse('learning_logs:index')) topics = Topic.objects.filter( topic = Topics.objects.get(id=topic_id)
owner=request.user) if topic.owner != request.user:
context = {'form': form} raise Http404
return render(request, --snip--
'users/register.html', context)