Tải bản đầy đủ (.pdf) (26 trang)

26 trang cheat sheet Python

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (20.22 MB, 26 trang )

Beginners Python
Cheat Sheet

Dictionaries

squares

= [x**2

formation. Each iam in a cicth

for x in range(1,

Slicing a list

‘bob’,

'ada',

First_two = finishers{:2].
Copyinga liet



copy_of_bikes

Hello world
print("Hello

nonane


List comprehensions

finishers = [‘sam',

Variables and Strings
V

Lists (cont.)

11)]

A simple dictionary

'bea']

+ bikes[:]

msg = “Hello world!”
print (msg)
‘albert’

last_name = ‘einstein’
name

= first name +

print (full_name)

'° ' + last name


TC
Nhi
Tooele ee,

ARE

TH

ga:

ROI

equals

Laie
So

I

Das

oy

-N'/.-..

bikes

= ['trek',

‘redline’,


Get the first item in a list
first_bike

= bikes[@]

Get the last item in a list
last_bike

= bikes{ -1]

Looping through a list
bike in bikes:
print(bike)

bikes
bikes..
bikes.
bikes..

= []
append( ' trek ' )
append( ' redline' )
append( ' giant ' )

Making numerical lists
squares = (]
for x ín range(1,

'giant']


11):

squares. append(x**2)

x == 42

x l= 42
x > 42

less

x < 42

than

or equal to

‘trek’

'color'

])

can

votel”)

lí-elif-else statements
= ®

= 16

ellie _price = 15

na á

TY

sbửao



xY

“)

name = input("What's your name?

print("“Hello,

“ + name

+ “!")

Prompting for numerical input


if

ticket_price


print(str(number) + ' is a favorite’)

sừyad

game_active = True
can_edit « False

elif age < 18:

through all the values

fav_numbers = {‘eric': 17, ‘ever’: 4}
for number in fav_numbers.values():

x ‹= 42

Assigning boolean values

if ageticket_price
< 4:

tee

User input

in bikes

Sane
if age >= 18:

print("You

An

fav_numbers = {‘eric': 17, ‘ever’: 4}
for name in fav_numbers.keys():
print(name + ' loves a number’)

x >= 42

‘surly’ not in bikes

i

Adding items to a list

:
is ” + alien[{

Looping through all keys

Looping

not equal
greater than

or equal to

Make a list


for

dimensions = (1920, 1080)

Condgitional tests

Lists
UC

color

fav_numbers = {'eric': 17, 'ever': 4}
for name, number in fav_numbers.items():
print(name + ' loves ' + str(number))

Making
a tuple

Concatenation (combining strings)
full

ACSBESNIG' 6 Value
print("The alien's

‘points’: 5}

Looping through
all key-value pairs

world!")


=

‘green’,

Aaiding anew kay-valie pair
alien['x_position'] « @

Hello world with a variable

first name

alien = {'color':

*
¬

input (*
Rts

St SNe eee

pi = input(“What’s
pi = float(pi)

-

2

the value of pi?


Python Crash Course

“)

Covers Python 3andPython2 |

nostarchpress.com/pythoncrashcourse

|-*3%.
:
lẻ

=

4


While loops
ecm,

Dp

Working with files

Classes

e

repeal

se)

A simple while loop

Reading a file and storing its lines

current_value = 1
while current_value <= 5:
print(current_value )
current_value += 1

class

Letting the user choose when to quit

Dog():
"""Represent
def

mse

=

while

msg != ‘quit’:
msg = input( "What's
print(msg)

your


message?

self.name

”)
def

«

greet_user():
"““Display a simple
”He11o!

class

”)

def

greet_user(username):
““"“Display a person alized greeting.””"
print("Hello,
" + u sername + “!")

pizza()

add_numbers(x,
y):
“"“"Add two numbers

return

sum

=

x

+

add_numbers({3,

print(sum)

5)

"

is

a

great

dog!”)

init

search


=

‘journal,txt'

open(filename,
‘w')
file object.write("I

as file object:
love programming.”)

Appending to a file
filename = ' Journal,txt'
with open(filename,
'a')

file object.write("\nI

as

file object:

love

making

games.")

(self,


dog.

name):

def

search(self):
"""Simulate searching."""
print(self.name +
is searching.”)
=

SARDog(

print(my dog.name
my_dog.sit()
my_dog.search()

+



is

return

the

sum.”””


Catching an exception
prompt = “How many tickets do
num tickets « input(prompt)

you

need?



try:

‘Willie’ )
a

search

dog.”)

Bele

and

y

+

Infinite Skills

ˆpepperoni ' )


Returning a value
def

sitting.”)

Initialize the sarđog. """
super().
init
(name)

my_dog

make_pizza(topping= 'bacon"
}:
““"Make a single-topping pizza.””'"
print(”Have a ” + + opping + ” pizzal”)

make_pizza(

is

Dog(‘*Peso')

“wun

jesse’)

Default values for parameters


make

with

sitting."""

SARDog(Dog):
"""Represent a

Passing an argument

def

line in lines:
print({ line)

inheritance
greeting.”

greet_user()

greet_user(

for

Writing to a file

name

4


‘siddhartha.txt’

open(filename)
as file_object:
lines = file object.readlines()

Filename

sit(self):
""“Simulate

print(my_dog.name
my_dog.sit()

A simple function

def

=

=

with
dog."""

print(self.name

my dog


print(

a

init
(self,
name);
"""Tnitialize dog object.”'

Functions

def

filename

Creating a dog class

As you're learning to program, it's helpful to think
about the real-world projects you'd like to create. It's
a good habit to keep an “ideas” notebook that you
can refer to whenever you want to start a new project.
if you haven't done so already, take a few minutes
and describe three projects you'd like to create,

num tickets = int(num_tickets)
except ValueError:
print("Please try again.")
else:
print("Your tickets are printing.")


Zen of Python
Díe

(s

Deftter

thay

If you have a choice between a simple and a complex
solution, and both work, use the simple solution. Your
code will be easier to maintain, and it will be easier
for you and others to build on that code later on.
More cheat sheets available at
chmatthes.github.|o/pcc/


Beginner's Python

Adding elements

Sorting a list

Cheat Sheet - Lists

You can add elements to the end of a list, or you can insert
them wherever you like ín a list.

Adding an element to the end of the list


The sort() method changes the order of a list permanently.
The sorted{) function returns a copy of the list, leaving the
Orlginal list unchanged. You can sort the ilems in a f(st in
alphabetical order, or reverse alphabetical order. You can
also reverse the onginal order of the list, Keep in mind that
jowercase and uppercase letters may affect the sort order.

users. appená( ' amy' )
Starting with an empty list

A list stores a series of items in a particular order.
Lists allow you to store sets of information in one
piace, whether you have just a few items or millions
of items. Lists are one of Python's most powerful
features readily accessible to new programmers, and
they tie together many important concepts in

users
users.
users.
users.

programming.

Defining a list

Removing elements

Making a list
users = [‘val',


"bob',

‘mia’,

‘ron’,

‘ned’]

Accessing elements

Individual elements in a list are accessed according to their
position, called the index. The index of the first element is
0, the index of the second element is 1, and so forth.
Negative indices refer to items at the end of the list. To get
4 particular element,

write the name of the list and then the

index of the element in square brackets

Getting the first element
first_user

= users[Ø]

Getting the second element
second_user

= users[1]


Getting the last element
newest_user

= users[-1]

Modifying individual items
Once you've defined a list, you can change individual
elements in the list. You do this by referring to the index of
the ilef you want to modily.

Changing an element
users[Ø] = ‘valerie’
users[-2] = ‘ronald’

users. sort()

Sorting a list permanently in reverse alphabetical

order

Inserting elements at a particular position
users.insert(0,
users.insert(3,

Use square brackets to deline a list, and use commas to
separate individual items in the list, Use plural names for
lists, to make your code easier to read.

Sorting a list permanently


= []
appená( ' vaÌ ' )
anpenád( ' bob ' )
append( 'mia' )

users.sort(reverse=True)

'joe')
'bea')

Sorting a list temporarily
print(sorted(users))
print(sorted(users, reverse=True))

You can remove elements by their position in a list, or by
the value of the item. If you remove an item by its value,
Python removes only the first item that has that vaiue

Reversing the order of a list

Deleting an element by its position

Looping through a list

users.reverse()

del users[-1]

Lists can contain millions of tems, so Python provides an

efficienf way to loop through afi the items ín a list. When
you set up a loop, Python pulls each item trom the list one
at a time and stores it in a temporary vanable, which you

Removing an item by its value
users. remove( ‘mia’ )

provide a name for. This name should be the singular
version of the list name

Popping elements

The indented block of code makes up the body of the
loop, where you can work with each individual item. Any
ines that are not indented run after the loop is completed.

If you want to work with an element that you're removing
from the fist, you can “pop” the element. If you think of the

list as a stack of items, pop() takes an item off the top of the

Printing all items in a list

Stack, By default pop() returns the last element in the list,
bul you can also pop elements from any position in the list.

Pop the last item from a

for


list

for

Pop the first item in a list
first_user = users.pop(@)

List length
The jen() function returns the number of items in a

list

Find the length of a list
* len(users)
have ” + str(num users)

user in users:
print("Welcome,

print("Welcome,

print(first_user)

num_users
print(”We

user in users:
print(user)

Printing a message for each item, and a separate

message afterwards

most_recent_user = users.pop()
print(most_recent_user)

_

What are lists?

+ ” users,")

“ + user +

“!")

we're glad to see you all!")

Python Crash Course ——
Covers Python 3 and Python 2
nostarchpress.com/pythoncrashcourse


Tuples

The range() function

Copying a list

You can use the range() function to work with a set of


To copy a list make a siice that starts at the first item and
Cia
ee a
eee eee
ee Se eee
this approach, whatever you đo to the copied list will affect
the orginal list as well.

numbers efficiently. The range{) function starts at 0 by
default, and stops one number below the number passed to
it, You can use the list() function to efficiently generate a
large lisf of nurnbers.

Printing the numbers 0 to 1000

finishers = ['kai', 'abe', ‘ada’,
copy_of_finishers = finishers[
; ]

for number in range(1991):
print(number)
1991):

= list(range(1,

10000@1))

There are a number of simple statistics you can run on a list
containing numerical data.


Finding the minimum value in a list
«

youngest

(93,

99,

66,

17,

85,

1,

35,

85,

1,

35,

82,

2,

77)


2,

77]

= min(ages)

Finding the maximum value
ages = [93, 99, 66,
oldest = max(ages)

17,

82,

Finding the sum of all values
ages = (93,
total_years

99, 66, 17,
= sum(ages)

85,

1,

35,

82,


2,

77]

Slicing a list
You can work with any set of elements from a list, A portion
Of a list is called a slice. To siice a fist start with the index of
the first item you wart, then add a colon and the (ndex after
the last ilem you wart. 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 fist.

Getting the first three items
finishers = ['kai', ‘abe’, ‘ada’,
first_three = finishers[:3]

Getting the middie three items
middle three = finishers[1:4]

Getting the last three items
last_three

= finishers[-3:]

Using a loop to generate a list of square numbers
squares = []
for x in range(1, 11):
square = x**2
squares.append( square)


Using a comprehension to generate a
numbers

‘gus’,

'zoe']

= [x**2

for

x in range(1,

list of square

= ['kai',

‘abe’,

‘ada',

'gus',

‘zoe']

Using a comprehension to convert a list of names to
upper case
‘abe’,

‘ada’,


upper_names = [name.upper()

'gus',

for dimension in dimensions:
print(dimension)

Overwriting a tuple
dimensions = (800,
print(dimensions)
dimensions

600)

= (1299,

999)

Visualizing your code
When you're first leaming about data structures such as
lists, it helps to visualize how Python is working with the
information in your program. pythontutor.com is a great tool
for seeing how Python keeps track of the information in a
list. Try running the following code on pythontutor.com, and
then run your own code
dogs * []
đogs
. append( 'wi11ie' )
đogs. appenó( 'hootz ' )


dogs .append( ‘peso’ )

dogs .append(' goblin’)

upper_names = []
for name in names:
upper_names.append(name.upper())

names = ['kai',

600)

Build a list and print the items in the list

11)]

Using a loop to convert a list of names to upper case
names

= (800,

Looping through a tuple

values you wan! lo store in the list. Then wrile a for loop to
generate ínput values needed to make the list

squares

Defining a tuple

dimensions

To write a comprehension. define an expression for the

Simple statistics

ages

“zoe']

You can use a loop to generate a list based on a range of
numbers or on another list. This is a common operation, so
Python offers a more efficient way to do it. List
comprehensions may look cornplicated at first; if so, use the
for loop approach until you're ready to start using
comprehensions

Making a list of numbers from 1 to a million
numbers

‘gus’,

List comprehensions

Printing the numbers 1 to 1000
for number in range(1,
print(number)

Making a copy of a list


Ä luple ¡s lke a list, excepf you car'† change the values tm a
tuple once I's defined. Tunles are good lor storing
information that shouldn't be changed throughout the lite of
a program. Tuples are designated by parentheses instead
of square brackets. (You can overwrite an entire tuple, but
you can't change the individual elements in a tuple.)

'zoe']

for name in names}

Styling your code
Readability counts

e Use four spaces per indentation level.
e Keep your lines to 79 characters or fewer.
e Use single blank lines to group parts of your
program visually.

for dog in dogs:
print("Hello " + dog + “!")
print("I love these dogs!")
print(“\nThese were my first
old_dogs = dogs[ :2]
for old_dog in old_dogs:
print(old_dog)

two dogs:”)

del dogs[@]

dogs .remove( ‘peso’ )
print(dogs)

More cheat sheets available at
ehmatthes.github.|o/pcc/


Beginner's Python
Cheat Sheet —
Dictionaries

You can store as many key-value pairs as you want ina
dictionary, until your computer runs out of memory. To add
a new key-value pair to an existing dictionary give the name
of the dictionary and the new key in square brackets, and
Set iI equal to the new value.
This also allows you to start with an empty dictionary and
add key-value pairs as they become relevant.
alien_@

Python's dictionaries allow you to connect pieces of
related information. Each piece of information in a
dictionary is stored as a key-value pair. When you
provide a key, Python returns the value associated
with that key. You can loop through all the key-value
pairs, all the keys, or all the values.

alien_@['x']

Use curly braces to define a dictionary. Use colons to


individual key-value pairs.

fo separate

Making a dictionary
= {‘color’:

‘green’,

‘points’:

5}

Accessing values

To access the value associated with an individual key give
the name of the dictionary and then place the key in a set of
square brackets. lÍ the key youre asking for ¡s not ín the
dictionary, an error will occur.
You can also use the get() method, which returns None
instead of an error if the key doesn’t exist. You can also
specify a detault value to use if the key is not in the
dictionary.

Getting the value associated with a key
-alien8 = {‘color’:

‘green’,


‘points’:

5}

print(alien_@[ ‘color’ ])

‘green'}

alien_color = alien_@.get(‘color'’)
alien_points = alien_@.get('points’,
print(alien_color)
print(alien_points)

‘points’:

5}

= 25

alien_@['speed']

@)

A dictionary only tracks the connections between keys
and values; it doesrt † trac& the order of ilemas in the
dictionary. If you want to process the information in order,
you can sort the keys in your loop.
# Store

people's


fav_languages

= {

favorite

languages.

‘sarah'; ‘c',
‘edward’: ‘ruby’,

= 1.5

oe

Adding to an empty dictionary
alien_@

values.

‘jen’: ‘python’,

= @

= {}

= 5

Modifying values


Looping through all the keys

You can modify the value associated with any key ina
dictionary. To do so give the name of the dictionary and
enclose the key in square brackets, then provide the new
value for that key.

‘green’,

# Change the alien's color and
alien_8[ 'color'] = ‘yellow’
alien_@['points'] = 18
print(alien_6)

‘points’:

5}

point

value.

chosen.

Looping through all the keys in order
for name in sorted(fav_languages.keys()):
print(name

You can remove any key-value pair you want from a

dictionaty. To do so use the del keyword and the dictionary
name, followed by the key in square brackets. This will
delete the key and its associated value
‘points’:

+ ":

“ + language)

Dictionary length
You can find the number of key-value pairs in a dictionary.

Finding a dictionary’s length
num_responses

+ len(fav_languages)

5}

đel alien_6[ 'points']
print(alien_8)

Visualizing dictionaries

# Show all the languages that have been
for language in fav_languages.values():
print (language)
# Show each person's favorite language,
#
in order by the person's name.


Removing key-value pairs

‘green’,

# Show everyone who's taken the survey.
for name in fav_languages.keys():
print (name)

Looping through all the values

Modifying values in a dictionary
alien_6 = {‘color';:
print(alien_0)

'python',

# Show each person's favorite language.
for name, language in fav_languages.items():
print(name + "; “ + language)

alien_6[ 'color'] = ‘green’

alien_@ = {'color’:
print(alien_6)

Getting the value with get()
= {‘color’:

‘green’,


Deleting a key-value pair

print(alien_@[‘points*])
alien_@

alien_@['y']

alien_6[ 'points']

Defining a dictionary

alien_@

= {‘color’:

You can loop through a dictionary in three ways; you can
foop through all the key-value pairs, all the keys, or all the

Looping through all key-value pairs

Adding a key-value pair

What are dictionaries?

connect keys and values, and use commas

Looping through a dictionary

Adding new key-value pairs


Try running some of these examples on pythontutor.com.

Python Crash Course
Covers Python 3 and Python 2
nostarchpress.com/pythoncrashcourse

|

Nesting —

Using

Nesting — Lists in a dictionary

A list of dictionaries

an OrderedDict

1

Storing dictionaries
in a list
# Start with
users = []

an empty

Storing lists in a dictionary


list.

# Make a new user, and add them
new_user = {
‘last’: ‘fermi’,
‘first’: ‘enrico'’,
‘username’: ‘efermi’,

to the

list.

them

as well.

# Show all responses for each person.
for name, langs in fav_languages.items():
print(name + ": ")
for lang in langs:
print("- " + lang)

Nesting

You can also define a list of dictionaries directly,
without
using append():

}


{

]

},

user

‘last’: ‘fermi’,
*first'°: ‘enrico’,
‘username’: ‘efermi’,
‘last’: ‘curie’,
‘first’: ‘marie’,
‘username’: ‘mcurie’,

# Show a11 information about each user.
for user_dict in users:
for k, v in user dict.items():
print(k + ”: ” + v}

print(”\n")

+
"Fi

# Show all information about each user.
for user_dict in users:
for k, v in user_dict.items():
print(k + ”: ” + v}

print(”\n”)

# Define a list of users, where each
#
is represented by a dictionary.
users = [

A dictionary of dictionaries

1

users. append(new_user)

{

person.

}

users .append(new_user)
# Make another new user, and add
new_user = {
‘last’: ‘curie’,
"first": ‘marie’,
‘username’: ‘mcurie’,

# Store multiple languages for each
fav_languages = {
'"Jen'; ['python', ‘ruby'],
'sarah': ['c'],

'eđward'; ['rnuby', 'go'],
'phil'; ['python', 'haskell"],

rf
el.

ona
el el

Maen

Tit,

ia’

Storing dictionaries in a dictionary
users

= {
*aeinstein': {
‘first’: ‘albert',
‘last’: ‘einstein’,
‘location’: ‘princeton’,
,

‘mcurie’: {
‘first’: ‘marie’,
‘last’: ‘curie’,
‘location’: ‘paris’,


}

},

for username, user_dict in users.items():
print("\nUsername: “ + username)
full_name = user đict['first'] + ”" ”
full name +« user đict['last']
location = user đict[ 'location' ]
print("\tFull name: ” + full name.title())
print("\tLocation: “ + location.title())

Levels
of nesting

Tai +07" si.

,

Preserving
the order of keys and values
from

collections

import

OrderedDict

# Store each person's languages,

# track of who respoded first.
fav_languages = OrderedDict()

keeping

fav_languages[ 'jen'] = ['python',
fav_languages[ 'sarah"' ] = ['“c']

fav_languages[ 'edward']
fav_languages[ 'phil']

= ['ruby',

= ['python',

'ruby']

'go']

"haske1l1']

# Display the results, in the same order they
# were entered.
for name, langs in fav_languages.items():
print(name + “:")
for lang in langs:
print(”- ” + lang)

Generating
a million dictionaries

"an!

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(19999996):
new alien « {}
new_alien[ 'color'] = ‘green’
new alien[ 'points'] « 5
new alien{[ 'x'] = 28 * alien num
new alien[ 'y'] = @
aliens. append(new_a1ien)
#

Prove

the

num_aliens

list

contains

= len(aliens)


print(“Number of aliens
print(num_aliens)

a million

aliens.

created:")

More cheat sheets available at
ehmatthes.github.lo/pcc/


Beginners Python

“Na

if statements
SeVECTA!

aoe

/SĐ

Comparison operators
>>>

age

=


19

>>>

age

<

21

age

<=

>>>

age

> 21

>>>

age

>=

sn

are while loops?


False

of a program and respond appropriately to that state.

You can write a simple if statement that checks one
condition, or you can create a complex series of if
Statements that idenitfy the exact conditions you're
looking for,

21

test is

or False.

an

P)

expression!

“SỐ

that



ak


A single equal sign assigns a value fo a variable. A double equa!
sign (==) checks whether two values are equal.
>>>

car

=

‘bmw’

ee

car
ar

===

‘bm

>>> car
>>> car
False

=
==

True

.


w

Y

as

sẻ vi

: +

>>>

>=

False

ing
DNNg

>>>

>>>

True s

dị"

>=

18:


print("You‘re

age

«

old

enough

to

vote!")

if

age

old

enough

to

vote!”)

17
>=


18:

print(”You

=

can"t

vote

yet,”)

12

age_@

or
G19

age_@
age

>>>
>>>

~

@

age Ø

@
« age
False ef.

age <
price
elif age
else:

tit
aA

=

5

price

=

18

and

age_1

>=

21


print("Your

= 23
>= 21

and

age 1

>=

21

Conditional

>=

cost

1s

$”

+

str(príce)

+

”.”)


tests with lists

ndition
COINS

= 22

ee

8
18:

price

21

heck
multi
Cục
URE

4:

&

if

ee


‘au
`
‘bmw

19

The if-elif-else chain

>>> age 1
>>> age@
True

Checking for equality

age

21

Using and to check multiple conditions

0

if

age

Conditional Tests
condltlonal

=


else:

False

true. You can use while loops to let your programs
run as long as your users want them to.

[rue

age

print(“You’re

While loops run as long as certain conditions remain

Â

a

if-else statements

rue

lf statements allow you to examine the current state

K

ceDpern


Simple if statement

age t= 18
True

What

ee

——

lf Statements
and While Loops
are if statements?

tie

Testing equality and inequality

Cheat Sheet —

What

arpa

Numerical comparisons

Testing if a value is in a

21


or

age

+ 18
>=?= 421

or

age_1
e
oe

~

1

>=

21

>=

21

>>>
>>>

players

‘al’ in

z ['al',
players

list
‘bea’,

‘cyn’,

'dale'|

True
ea

>>> ‘eric’
False

in

players

Ignoring case when making a comparison
>>>

car

=

Boolean


‘Audi’

>>> car.lower()
True

«»

Checking for inequality
>>> topping
>>> topping
True

=
!=

values

‘audi’

;

‘mushrooms
‘anchovies’

Simple boolean values
game
_ active
= True
can edit = False


Python Crash Course PETER
Covers Python 3 and Python 2

nostarchpress.com/pythoncrashcourse


Conditional

tests with lists (cont.)

Testing if a value is not in a list
banned_users =
user « ‘erin’



if

banned_users:

user

not

[‘ann',

in

print(”You


can

if

=

‘chad’,

‘dee’]

prompt

=

prompt

+=

“repeat

prompt

+=

"\nEnter

message

play!”)


while

else:

=

if

have

no

player.title())

players

input

message



+

your

name

name?


input("“How
int(age)

old

+=

“repeat

prompt

+=

"\nEnter

+

if

"\nrell

message
active

you.”

‘quit’

to


end

the

banned users

I'1l

prompt
prompt

program.

you?

to

you.”

‘quit’

to

end

the

1'11


=

program.

vote!”)

can't

while

vote

else:

#

players.append(player)

‘quit’:
False

name = raw_input("What's
print{"Hello,
“ + name +

your
”.")

while


=

True:
name = input("\nWho
print("Nice to meet

are you?
you,
+

”}
name

name?

city

==

'quit
';

else:

print("I've

”)

been


to

+

city

Accepting input with Sublime Text
.“

el

£?š

+

“!")

Removing all cats from a list of pets
pets

while
1

=

['dog’,
'cat',
‘rabbit’,

‘dog’,

'cat']

'fish',

current_number

‘cat’
in pets:
nets.remove(
'cat ' )

print(pets)

current_number <= 5:
print(current_number)
+=

1

”!”)

input(prompt)

print(pets)

Counting to 5

+

break


=

loops

An infinite loop

True:

if

Use raw_input() in Python 2.7. This function interprets all input as a
string, just as input() does in Python 3.

while

"\nAdd a player to your team.”
“\nEnter
‘quit’ when you're done.

yet.”)

Accepting input in Python 2.7

=

'helen']

print(”\nYour team: ”)
for player in players:

print(player)

= "\nWhat cities have you visited?”
+= "\nEnter
‘quit’ when you're done.

city

current_number

‘gary’,

continue



Using break to exit a loop

“)

else:
print(™\nYou

and

back

input(prompt)
==


‘fred’,

print (message)

are

can

something,

it

['eve’,

players = []
while True:
player » input(prompt)
if player == ‘quit’:
break
elif player in banned users:
print(player + " is banned!")

‘quit’:

me

+=

=


else:

“.")

prompt
prompt

age >= 18:
print(“\nYou

While

f=

=

”)

Accepting numerical input
=
«

to

‘quit':

prompt

active = True
while active:

message «

input("What's

print("Hello,

age
age

and

back

input(prompt)

prompt

Simple input
=

I=
=

something,
it

Using a flag

yet!")


Vv

name

me

print (message)

player in players:
print( "Player:
+

Accepting

“"

message

message

[]

print("We

if

“\nTell

players:


for

Using continue in a loop

Letting the user choose when to quit

Checking if a list is empty
players

While loops (cont

(cont.)

loops

While

More cheat sheets available at
ehmatthes.github.io/pcc/

‘cat’,


Positional and keyword arguments

Beginners Python
Cheat Sheet —

Return values


Returning a single value

Functions
What

def

Using positional arguments

are functions?

def

Functions are named blocks of code designed to do

one specific job. Functions allow you to write code
"

4

need,

04g
NA.
and
returnthe information

generate. Using functions effectively makes your
programs easier to write, read, test, and fix.
Defining

,
TH:

rir

they

deal
name
<

>

name):

oe sa)

F si

asp + exerarmeeg
name +

âä

11

is




“.")

def build_person(first, last):
"“""Return

name):

"""Display
print("\nI

information about
have a “ + animal

print("“Its

name

"

+

a
+

name

person

pet."""
",")


+

“.")

musician

name='harry
')

animale ‘dog’)

greeting.””

a single argument

Using

greet_user(username):
"""Display a simple greeting.”””


+

greet_user(' jesse’)
greet_user(

diana’ )

greet_user(


‘brandon’

)

username

+

”!”)

build person(

def

None

to make

a “ + animal
+ ”.")
is “ + name + ".")

a

if

have

a


name:

t
đ
print("Its

name

describe pet(hamster,
describe pet( snake)

+

_

age=None):
information

=

{'first':

first,

last:

last}

'age' ]


ô=

age

person

=

_P

:

build

-P

person('jimi',
( 3

hendrix,

l2.
s06
anis
',
(3

person


12
TH
oplin
J9P
)

Visualizing functions
ng

optional

animal

hendrix)

person.

print (musician)

describe pet(animal, name=None):
Display information about a —
print("\nI

last}

age:

musician

'*hamster")


an argument

‘last’:

.

build person(first,
last,
“““Return a dictionary of

musician
build
or3nt(sasiclan)

describe pet(name, animal=‘ dog’):
"""Display information about a pet.”"”
have
name

information

jimi’,

5

person[

print("\nI
print("Its


Sạn 2X )

Returning a dictionary with optional values

if

describe pet(‘willie’)

print(“Hello,

«

print(musician)
`
s5 y6

person

def

of

first,

person

about

describe _pet('harry',


def

= {'first':

return

Using a default value

;

a dictionary

about a person

“one

to a function

name.’

ti)



return

Passing information

full


Returning a dictionary

def

greet_user()

last):

formatted

< ies A226,

e

Default values

Passing

nm Sarees

neatly

owe

describe_pet(animal,

describe pet(names'willie',

t("Hello!")


en

a

print (musician)
:
peer

Using keyword arguments

describe _pet(animal='hamster’,

Making a function
def greet_user():
“" "Display a simple
prin

name(first,

MUSA CT

.

describe pet(‘hanster','willie')
harry")

is

full


“""Return

return full name.title()

describe pet('dog’,
def

a function
F
bie

2Q

pei
WR scodbis
print("“Its

4

once that can then be run whenever you need to

0/144
in ormation they

describe pet(animal,

get

Python


+

a
is “ + name

+

=
“.”)

some

Of

(nese

Crash

exa

Course

Covers Python 3 and Python 2
nostarchpress.com/pythoncrashcourse

‘harry')
|

|


27

)


Passing an arbitrary number of arguments

Passing a list to a function

Modules

homes

Passing a list as an argument

Storing a function in a module

def greet_users(names):
“""Print a simple greeting
for name in names:
msg = “Hello, " + name

to everyone.”"”
+ “!"

print(msg)

usernames = [‘hannah',
greet_users(usernames)


‘ty’,

‘margot']

Allowing a function to modify a list

The following example sends a list of models to a function for
printing. The original list is emptied, and the second list is filled.

def print_models(unprinted, printed):
“""3d print a set of models."""
while unprinted:
current_model = unprinted. pop()
print("Printing “ + current_model)
printed. append(current_model)
# Store some unprinted designs,
# and print each of them.
unprinted = [‘phone case’, ‘pendant’,
printed « []
print_models(unprinted, printed)

Collecting an arbitrary number of arguments
def make_pizza(size, *toppings):
““"“Make a pizza."""
print("\nMaking a “ + size + “ pizza.")
print( “Toppings: ”)
for topping in toppings:
print("- " + topping)
# Make three pizzas with different toppings.

make _pizza('small', ‘pepperoni’)
make_pizza('large’', ‘bacon bits’, 'pineapple')
make_pizza('medium’, ‘mushrooms’, ‘peppers’,
‘onions’, ‘extra cheese’)

Collecting an arbitrary number of keyword arguments
def

build profile(first, last, **user_info):
“““Build a user's profile đictionary.”""
# Build a dict with the required keys.
profile = {'first'; first, ‘last’: last}

# Add any other keys and values.

'ring']

for

print(“\nUnprinted:", unprinted)
print("Printed:", printed)

return

Preventing a function from modifying a list

The following example is the same as the previous one, except the
onginal list is unchanged atter calling print_modets().

def print_models{unprinted, printed):

“""3d print a set of models.”""
while unprinted:
current_model = unprinted. pop()
print("Printing " + current_model)
printed. append(current_model)
# Store some unprinted designs,
# and print each of them.
original = [‘phone case’, ‘pendant’,
printed = []
print_models(original[:], printed)
print("\nOriginal:", original)
print(”Printed:”, printed)

key, value in user_info.items():
profile[key] = value

# Create two users with different kinds
#
of information.
user_@ = build profile(‘albert', ‘einstein’,
location‘ princeton’ )
user 1 = build profile('marie’, 'curie',
location='paris', field='chemistry')
print(user_9Ø)
print(user_1)

What's
|

‘ring’]


profile

\

Ol,

def make_pizza(size,

*toppings):

"“"Make a pizza."""

~

print("\nMaking a “ + size
print("Toppings:")
for topping in toppings:
print("- “ + topping)

+ " pizza.")

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')

Importing a specific function

Only the imported functions are available in the program file.

from

pizza

import

make_pizza

make_pizza('medium', ‘pepperoni’ )
make_pízza('small', ‘bacon’, ‘pineapple’)

Giving a module an alias
import

pizza

as p

p.make_pizza('medium', ‘pepperoni')
p.make_pizza('small', ‘bacon’, ‘pineapple')

Giving a function an alias

from

pizza

import

make_pizza

as mp

mp('medium', ‘pepperoni’)
mp('small', ‘bacon’, ‘pineapple')

Importing all functions from a module

Don't do this, but recognize it when you see it in others’ code. It

the best way to Structure
a function?
:

File: pizza. py

.

;

;

1)


21 2,

4

.

i

can result in naming conflicts, which can cause errors.

from pizza

import

*

make_pizza('medium’, ‘pepperoni’ )
make pizza('small', ‘bacon’, 'pineapple')

More cheat sheets available at
ehmatthes.github.|o/pcc/


Beginner's Python
Cheat Sheet - Classes

Creating and using a class (cont.)

Classes are the foundation of object-oriented

programming. Classes represent real-world things
you want to model in your programs: for example

dogs, cars, and robots. You use a class to make

objects, which are specific instances of dogs, cars,

and robots. A class defines the general behavior that
a whole category of objects can have, and the

information that can be associated with those objects.

Classes can inherit from each other — you can
write a class that extends the functionality of an
existing class. This allows you to code efficiently for a
wide variety of situations.

my_car

=

Car('auđi',

‘a4’,

Creating and using a class

The __init__() method for a child class

Calling methods


class

my car.fill tank()
my car.drive()

Creating multiple objects

neti›0gs

!na

L2

0/0.

j

new_car

def

attempt

to

model

a


car.”""

_init__(self,
make, model, year):
“““Initialize car attributes.”
self.make = make
self.model
= model
self.year = year
# Fuel capacity and level
self.fuel_ capacity = 15
self.fuel_level
= @

def

31/ues

m

@

=

Car('audi',

=

5


‘ad’,

class

2016)

in

gallons.

fill_tank(self):
““"“Fill gas tank to capacity.”""
self.fuel level
= self.fuel capacity
print(“Fuel tank is full.”)
drive(self):
"""Simulate driving.”””
print("The car is moving.”)

update
fuel level(self,
new level);
""“Update the fuel level.”""
if nmew_level <= self.fuel capacity:
self.fuel level
= new_level
else:
print("The tank can't hold that

add


fuel(self,

"""Add

fuel

to

ElectricCar(Car):
def

charge(self):
nen
“""“Fully charge the vehicle.
self.charge level = 199
print("The vehicle is fully charged.")

Using child methods and parent methods
my_ecar

much!")

=

ElectricCar('tesla',

‘model

s',


2016)

my_ecar.charge()
my ecar.drive()

amount):
the

tank."""

(self.fuel level
+ amount
<=> self.fuel capacity):
self.fuel level
+= amount
print("Added fuel.”)
else:
print("The tank won't hold that

'“NTiaa

cars.

-~snip-

Finding your workflow

if


Naming conventions

car."""

Adding new methods to the child class

Writing a method to increment an attribute's value
def

electric

# Attributes specific
to electric
# Battery capacity in kWh.
self.battery size = 78
# Charge level in %.
self.charge level
= @

ư/Ve@ldi

Writing a method to update an attribute's value

The Car class

def

IDCAati!

an


init.
(self, make, model, year):
“"“"Initialize an electric
car.””"
super().
init (make,
model, year)

Modifying attributes

my_new_car.fuel_level

def

def

Modifying an attribute directly

if) ©

ElectricCar(Car):
"“""A simple model
of

my can = Car(‘audi',
‘a4’, 2016)
my Old car = Car(‘subaru’,
‘outback’,
2013)

my truck + Car('toyota',
‘tacoma’,
2010)

my

Car({):
“""“A simple

2016)

Accessing attribute values

WHie

class

{£ ¿{

Creating an object from a class

print(my_car.make)
print(my_car.model)
print(my_car.year)

What
are classes?

'


Class inheritance

much.”)
PYTHON
CRASH CoUvasE
a


Class

importing Classes

inheritance (cont.

Classes in Python

dy

Overriding parent methods
ElectricCar(Car):
--snip-def fill_tank(self):
““"“Display an error message.””"
print("This car has no fuel tank!”)

Classes should inherit from object

class

class


instances
as attributes

class

A Battery class

class Battery({):
“"“"“A battery
--snip--

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 = @
def get_range(self):
“""Return the battery's
if self.size == 7@:
elif


return

248

return

278

self.size

== 85:

electric

attempt

to model

# Attribute specific to electric
self.battery = Battery()

for

an electric

Using the instance
my_ecar.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()


x',

class ElectricCar(Car):
def init__(self, make, model, year):
super(ElectricCar, self). init (
make, model, year)

car."""

car."""

2016)

Storing objects in a list

Importing individual classes from a module
my_cars.py
car import

Car,

ElectricCar
‘beetle’,

2016)

= car.Car(
*volkswagen',
my_beetle.fill_tank()
my_beetle.drive()


‘model

s',

= car.ElectricCar(
'tesla', ‘model s',
my_tesla.charge()
| tesla.drive()

my_beetle

import

2016)

to hold

2016)

‘beetle’,

ElectricCar
a fleet

of cars.

= []

# Fill the gas cars, and charge

for car in gas_fleet:
car.fill_tank()
for ecar in electric_fleet:
ecar.charge()

electric

cars.

print("Gas cars:", len(gas_fleet))
print("Electric cars:", len(electric_fleet))

*

= Car( ‘volkswagen’,

lists

Car,

# Make 508 gas cars and 2506 electric cars.
for _ in range(500);
car = Car(‘ford’, ‘focus’, 2016)
gas_fleet.append(car)
for _ in range(250):
ecar = ElectricCar( 'nissan', 'leaf', 2916)
electric_fleet.append(ecar)

Importing all classes from a module
car


# Make

import

electric_fleet

(Don? do this, but recognize it when you see it)

from

car

gas_fleet = []

‘beetle’,

my_tesla

A fleet
of rental cars

from

car

my_beetle

cars.


class ChildClassName(ParentClass):
def init__(self):
super(ClassName, self). init (}

The ElectricCar class in Python 2.7

ElectricCar(Car):
“""A simple model of an electric
~-snip--

import

def charge(self):
““"Fully charge the vehicle."""
self. battery.charge
level = 100
print(”The vehicle is fully charged.")
'model

a car."""

Importing an entire module

def init__(self, make, model, year):
“""Initialize
an electric car."""
super().. init_ (make, model, year)

Car(object):


Child class __init__() method is different

cars."""

my tesla = ElectricCar('tesla’,
2016)
my_tesla.charge()
my_tesla.drive()

ElectricCar(Car):

= ElectricCar('tesla',

Car():
“""A simple
~-snip—

and

my_beetle = Car('volkswagen',
my_beetle.fill_tank()
my_beetle.drive()

--snip--

my_ecar

class

from

range.””"

Using an instance
as an attribute
class

class

car.py

gas

ClassName(object):

The Car class in Python 2.7

Storing classes in a file
“"“"Represent

2.7

2016)

More cheat sheets available at
ehmatthes.github.lo/pcc/


Beginners Python
Cheat Sheet —
Files and Exceptions

What are files? What are exceptions?
Your programs can read information in from files, and

Reading from a file (cont.)

File paths (cont.)

Storing the lines in a

Opening a file using an absolute path

filename
with

=

f_path

‘'siddhartha.txt'

open(filename)

lines
for

list

«

as


f

with

obj:

Opening a file on Windows

line in lines:
print(line.rstrip())

ssing

the

Ww

Windows will sometimes interpret forward slashes incorrectly. tf
you run into this, use backsiashes in your file paths
f path

arourmen

with

files, and you can store Python structures such as
lists in data files.
Exceptions are special objects that help your


programs respond to errors in appropriate ways. For
example if your program tries to open a file that
doesn't exist, you can use exceptions to display an

informative error message instead of having the
program crash.

with

«

with

=

f.write("I

f.write("I

Appending to a

with

Reading an entire file at once

with

=

re


a

ce

s

try:

=

love

love

‘w')

as

print(5/@)
except

#:

creating

new

games.\n")


f

'programming.txt'

f.write("I
f.write("I

also
love

‘'a')

as

can‘t

divide

by

zero!”)

Handling the FileNotFoundError exception

file

open(filename,

ZeroDivisionError:


print(“You

programming! \n")

name

=

'siddhartha.txt°

try:

with

f:

love working with data.\n")
making apps as well.\n")

Pyti

open(f

lines

name)

as

f


oh]:

= f_obj.readlines()

except FileNotFoundError:
msg = “Can't find file
print(msg)

File paths
When

LAI

Handling the ZeroDivisionError exception

'siddhartha.txt"

open(filename) as f obj:
contents = f_obj.read()

.

YUL

‘w') as f:
programming!”")

‘programming.txt'


open(filename,

filename

7

Vy!

Writing multiple lines to an empty file

Reading from a file

filename

iF

‘programming.txt'

open(filename,
f.write("I
love

filename

“C:\Users\ehmatthes\books\alice.txt”

The try-except block

Writing to an empty file
filename


=

open(f_path)
as f_obj:
lines = f_obj.readlines()

you to work with a wide variety of information; writing

to files allows users to pick up where they left off the
next time they run your program. You can write text to

“/home/ehmatthes/books/alice.txt"

open(f_path)
as f_obj:
lines
f_obj.readlines()

f_obj.readlines()

Writing to a file

they can write data to files. Reading from files allows

=

{@}.".format(f_name)

Knowing which exception to handle

}

np

F

fo

Know

wheal

aind

of

ex:

non

in

print(contents)

Reading line by line

Each line that's read trom 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

itis would result in when printing to the terminal
filename

with

=

‘siddhartha.txt’

open(filename) as f_obj:
for line in f obj:
print(line.rstrip())

Opening a
#

path

with

file from a subfolder
=

open(f

lines
for

“text_files/alice.txt"


line

path)

=
in

as

#_obj:

f_obj.readlines()
lines:

print(line.rstrip())

Python Crash Course
Covers Python 3 and Python 2
nostarchpress.com/pythoncrashcourse

PYTHON
CRASH COURSE


The else block

Failing silently

Storing data with json


The try block should only contain code that may cause an
error. Any code that depends on the try block running
Successfully snould be piaced in the eise block.

Sometimes you want your program to just continue running
when it encounters an error, without reporting the error to
the user. Using the pass statement in an else block allows
eee enc)

The json module allows you to dump simpie Python data
structures into a file, and joad the data from that file the
next time the program runs. The JSON data format is not
specitic to Python, so you can share this kind of data with
people who work ín other languages as well.

Using an else block
print(“Enter

two numbers.

I'll

divide

them.”)

x = input(“First number: “)
y = input("Second number: “)

try:


result = int(x) / int(y)
except ZeroDivisionError:
print(“You can*t divide by
else:
print(result)

zero!)

Preventing crashes from user input

Without the except block in the following example, the program

wouild crash if the user tries to divide by zero, As written, it will
handie the error gracefully and keep ninning.

"“""A& simple calculator
print(“Enter
print("Enter

for division only.”""

two numbers. I'll
‘q‘ to quit.”)

divide

them.”)

while True:

x = input("\nFirst number: “)
if x == ‘gq’:
break
y = input("Second number: ”)
if y == 'q':
break

try:

result = int(x) / int(y)
except ZeroDivisionError:
else:

print(“You

can't divide by zero!”)

print(result)

Deciding which errors to report

Well-wnitten, properly tested code is not very prone to
internal errors such as syntax or logical errors. But every
time your program depends on something external such as
user input or the existence of a file, there's a possibility of
an exception being raised.
It's up to you how to communicate
Sometimes users need ta know if a
sometimes it’s better to handle the
expenence will help you know how


errors to your users,
file is missing;
error silently. A little
much to report,

Using the pass statement in an else block
f_names

= ["alice,txt', 'siddhartha.txt',
'moby_dick.txt', 'little women.txt' ]

for f name in f names;
# Report the length of each file found.
try:
with open(f_ name) as f_obj:
lines = f_obj.readlines()
except FileNotFoundError:
# Just move on to the next file.
pass
else:
num_lines = len(lines)
msg = "{Ø} has {1} lines.".format(
f name, num_lines)

print (msg)

Avoid bare except blocks

Exceptlon-handling code should catch specitic exceptions

that you expect fo happen during your program's execution.
A bare except block will catch ail exceptions, including
keyboard interrupts and system exits you might need when
forcing a program to close.

lf you want !o use a trự block and you re not sure which
exception to catch, use Exception. It will catch most
exceptions, but still allow you to interrupt programs

Knowing how to manage exceptions is important when
working with stored data. You'll usually want to make sure
the data you're trying to load exists before working with it.

Using json.dump({) to store data
“""Store
import

some

json

numbers

= [2,

“""Load
import

some


try:

# Do something
except Exception as e:

print(e,

type(e))

previously

stored

numbers."""

Making sure the stored data exists
=

Printing the exception

13]

print(numbers)

f name

# Do something
except Exception:
pass


11,

filename = ‘numbers. json’
with open(filename) as f_obj:
numbers = json. load(f_obj)

Don't use bare except blocks

try:

7,

json

json

Use Exception instead

5,

Using json.load() to read data

import

# Do something
except:
pass

3,


filename = 'numbers. json `
wíth open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)

intentionally.
try:

numbers."""

try:

‘numbers. json’

with

except

open(f_name) as f_obj:
numbers = json. load(f_obj)
FileNotFoundError:

msg = “Can’t find {@}.".format(f_name)

else:

print(msg)

print(numbers)

Practice with exceptions.


Take a program you've already written that prompts for user
input, and add some error-handling code to the program.

More cheat sheets available at
ehmatthes.github.| 0/pcc/


A failing test (cont.)

Building a testcase with one unit test

Running the test

To build a test case, make a class that inherits from

unittest. TestCase and write methods that begin with test_.

Save this as test_full_names.py

class

A unit test verifies that one specific aspect of your

code works as it's supposed to. A test case is a

import

ERROR:


Test

NamesTestCase(unittest.TestCase):
“““Tests for names.py."""

def test_first_last(self):
""“"“Test names like Janis 1oplin."""
full_name = get_full_name('janis',
*4oplin"'}
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 Jess than

0.001 seconds, and the OK lets us know that ail unit tests in the
fest case passed.

Using the function
from

full_names

import


get full name

janis = get full name('janis',
print(janis)
bob = get_full_name('bob',
print (bob)

'joplin')

'đylan")

like

Janis

Joplin.

„NamesTestCase)

*joplin')

TypeError: get_full_name() missing
positional argument: ‘last’
1 test

FAILED

in


1 required

9.901s

(errors#1)

Fixing the code

When a test fails, the code needs to be modified until the test
passes again. (Don? make the mistake of rewriting your tests to fit
your new code.) Here we can make the middie name aptional.

def get_full_name(first, last, middle=""):
"““Return a full name,**
if middle:
full name ô {đ} {1} {2}".format(first,
middle, last)
else:
full_name = “{@} {1}".format(first,
last)
return full_name.title()

A function
to test
Save this as full_names.py

Save this as names.py

test first last (_ main_


names

Traceback (most recent call last):
File “test_full_names.py”, line 16,
in test_first_last

Ran

A passing test

def get_full_name(first, last):
"“"Return a full name."""
full name « “{@} {1}".format(first,
return full name.title()

00 Hate atacaaet

E

get_full_name

collection
of unit tests which verify your code’s
behavior
in a wide variety of situations.
Testing a function:

When you change your code, it's important to run your existing

Đen. TT'VN Bế Pa 002aThoe ia Chiara

existing behavior.

Running the test

Modifying the function

last)

Weil modify get_full_name() so it handles middle names, but
well do it in a way thal breaks existing behavior.

def get full name(first, middle, last):
““"Return a full name.”""
full name = “{@} {1} {2}".format(first,
middle, last)
return full_name.title()

Now the test should pass again, which means our original
functionality
is still intact.

Ran

1 test

in 0.000s

OK

Using

the function
from full_names
john

import

get_full_name

= get_full_name(
' john',

print(john}

david = get_ full name( 'david',
print(david)

‘lee’,
‘lee’,

"hooker')
‘roth')

Python Crash Course
Covers Python 3 and Python 2
nostarchpress.com/pythoncrashcourse

M

import unittest
from full_names


Why test your code?
When you write a function or a class, you can also
write tests for that code. Testing proves that your
code works as it's supposed to in the situations it's
designed to handle, and also when people use your
programs in unexpected ways. Writing tests gives
you confidence that your code will work correctly as
more people begin to use your programs. You can
also add new features to your programs and know
that you haven't broken existing behavior.

s

Beginners Python
Cheat Sheet —
Testing Your Code

Testinga function (cont.)


Adding

new

Testing
a class

tests


A class
to test

Testing middie names

We've shown that get_full_name()
works for first and fast
names. Let's test that it works for middie names as well.
import unittest
from full_names

import

Save as accountant
py
class

get_full_name

def test_first_last(self):
“"““Test names like Janis Joplin.“""
full name = get full name( 'janis',
*4oplin')
self.assertEqual(full_
name,
‘Janis Joplin’)
test_middle(self):
“““Test names like David Lee Roth."""
full name = get_full_name( ‘david’,
‘roth’,


‘lee’)

self.assertEqual(full_
name,
"David Lee Roth’)

def

import unittest
from accountant

A variety of assert

def test_initial_balance(self):
# Default balance should be @.
acc * Accountant(})
self.assertEqual(acc.balance, 8)

methods

b)

Verify that x is True, or x is False
assertTrue(x)
assertFalse(x)

Rum
:
Ran




ning

100)

the

class

Accountant."""

setUp(self):
self.acc * Accountant()

100)

def test_deposit(self):
# Test single deposit.
self.acc.deposit
(100)
self .assertEqual(self.acc.balance,

10@)

# Test multiple deposits.
self.acc.deposit(100)
self.acc.deposit(
100)

self .assertEqual(self.acc.balance,

300)

# Test single withdrawal.

self.acc.deposit (1060)
self.acc.withdraw(10@)
self.assertEqual(self.acc.balance,

in 6,00@s

nai

unittest .main()

Running

the

tes

ee

Ran 3 tests in @.@@1s
OK

Verify an item is in a list, or not in a list
assertIn(item, list)
assertNotIn(item, list)


@)

def test_withdrawal(self):

the test

1 test

for

# Test non-default balance.
acc * Accountant(196)
self.assertEqual(acc.balance,

Accountant

# Test non-default balance.
acc = Accountant(190)
self.assertEqual(acc.balance,

Accountant

def test initial balance(self):
# Default balance should be @.
self.assertEqual(self.acc.balance,

unittest.main()

Verify that a==b, or a !=b

assertEqual(a, b)
assertNotEqual(a,

import

import

TestAccountant(unittest.TestCase):

“"“Tests

def

class TestAccountant(unittest.,TestCase):
""*Tests for the class Accountant."""

0.000s

OK

class

deposit(self, amount):
self.balance += amount

For the first test, we'll make sure we can start out with different
initial balances. Save this as test_accountant.py.

The two dots represent two passing tests.


in

import unittest
from accountant

Building
a testcase

Running the tests

2 tests

Using stUp) to support multiple test

The instance self .acc can be used in each new test.

account.”""

def withdraw(self, amount):
self.balance -= amount

unittest.main()

Ran

Accountant():
""*Manage a bank

def init__(self, balance«9):
self.balance = balance


class NamesTestCase(unittest.TestCase):
“""Tests for names.py."""

def

The setUp() method

More cheat sheets available at
ehmatthes. github.jo/pcc/

900)


Beginner's Python
Cheat Sheet - Pygame
What is Pygame?
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 rect objects (cont.)

Starting a game
ee

Useful rect attributes

Once you have a rect object, there are a number of attributes that
are useful when positioning objects and detecting relative positions

of objects. (You can find more attributes in the Pygame
documentation.)

An empty game window
import

sys

import

pygame

def

as

#

pg

and

set

up

screen

screen.


aspects of your game that make it interesting.

#

Start

while

main

loop.

True:
#

Start

for

event

$

$

sudo apt-get
install python3-dev mercurial
libsdl-imagel.2-dev
libsdl2-dev
libsdl-ttf2.0-dev

pip install
--user
hge+http: //bitbucket.org/pygame/pygame

Pygame on OS X

This assumes you've used Homebrew to install Python 3
$
$

brew install hg sdl
pip install
--user
herhttp:

sdl image

sdl

ttf

//bitbucket.org/pygame/pygame

Pygame on Windows

run

screen.

The display.set_mode() function accepts a tuple that defines the

Screen size.

Colors are defined as a tuple of red, green, and blue values,
value ranges
from 0-255
«=

(230,

2309,

Each

230)

color)

rect objects

If it’s a .wehl file, use pip to install Pygame
>

python

-m

pip

install


--user

To test your instafatlon, open a terminal session and try to import
Pygame. if you dont get any error messages, your installation was
successful.
$

python

>>>

>>>

import

pygame

=

(190,

pg.Rect(199,

190,

199,

3,

15)


190)
color,

bullet_rect)

Working with images
Many

lets.

f?

3 0arneE

ãft

Loading an image
ship

=

pg.image.
load( '° images/ship. bep ' )

Getting the rect object from an image
ship_rect

=


ship.get_rect()

Positioning an image

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 a ship object al the bottom center of the screen.
ship rect.midbottom

pygame -1., 9, 2a8-cp35-none-win32.whl

Testing your installation

s

dim = (1200, 800)
« pg.display.set_mode(screen_dim)

Setting a custom background color

Pygame

rect

color

pe.draw.rect(screen,

screen.fill(bg


Find an installer af
hitos//oitbucket. org’ pygame pygamedownicads/ or
http2//www.lic_ uci. edu/~gohike’/pythoniibs/#pygame
that matches
your version of Python. Run the installer file if it’s a .exe or .msi file.

screen_rect.centery

screen_rect.height

# Tuples
screen_rect,center
screen_rect.size

bullet

Setting a custom window size

be color

rect.width,

object, a color, and a rect. This function fills the given rect with the
given color

_game()

screen
screen


screen_rect.bottom

and height of the rect. The draw.rect() function takes a screen

pg.display.flip()

Pygame on Linux

values:

You can create a rect object from scratch. For example a small rect
object that's filled in can represent a bullet in a game, The Rect()
class takes the coordinates of the upper left comer, and the width

event in pg.event.get():
if event.type == pg.QuIT:

Refresh

y

screen_rect.right

Creating a rect object

loop.

sys.exit()
#


and

rect.centerx,

screen

screen = pg.display.set_mode((1200,
89Ø))
pg.display.set_caption("Alien
Invasion")

in building games, which lets you focus on the

x

rect.left,

screen_rect.top,

run_pgame():
# Initialize

pg.init()

Pygame takes care of many of the lower-level tasks

Individual

screen


=

screen_rect.midbottom

Getting the screen rect object

We already have a screen object; we can easily access the rect
object associated
wilh the screen.
screen_rect

=

screen.get_rect()

Finding the center of the screen

Rect objects have a center attribute which stores the center point.
screen_center

=

screen_rect.center

Python Crash Course

PYTHON

CRASH


Covers Python 3 and Python 2

nostarchpress.com/pythoncrashcourse

|

COURSE


Responding to mouse events

Working with images (cont.)

Pygame groups (cont.)

Drawing an image to the screen

Once an image is loaded and positioned, you can draw it to the
screen with the biit() method, The biil() method acts on the screen
object, and takes the image object and image rect as arguments
*#

Draw

ship

to

screen.


screen.blit(ship,

Game objects such as ships are often written as classes. Then a
biitme”) method is usually defined, which draws the object to the
screen
blitme(self):
“"““DOraw ship at

current

location.

self .screen.blit(self.image,

“wn

self.rect)

Responding to keyboard input
yoarne

waiches

Maa

Responding to the mouse button
for

ship_rect)


The blitme() method

def

Removing an item from a group

game, so you dont waste memory and resources.

event in pg.event.get():
if event.type == pg.MOUSEBUTTONDOWN:
ship.fire bullet()

mouse pos

=

pg.mouse.get pos()

Collisions between a single object and a group

Clicking a button

You nigh! 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()

keys.

for

pg.sprite.spritecollideany(ship,
ships left
-= 1

in

<

+=

len(collisions)

*

alien

point

value

pg.event.get():


event.type == pg.KEYDOWN:
if event.key == pg.K_ RIGHT:
ship rect.x += 1
elif event.key «= pg.K_LEFT:
ship rect.x
-= 1
elif event.key == pg.K_SPACE:
ship.fire_bullet()
elif event.key == pg.K_q:
sys.exit()

Rendering text

Making and filling a group

An object that will be placed in a group must inherit from Sprite.
from
def

Responding to released keys

pygame.sprite

import

Sprite,

Group

Bullet(Sprite):


def

draw

def

update(self):

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 fort, with a font size of 48. The font.render()
function is used fo 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

bullet(self):

When the user releases a key, a KEYUP event is triggered.
event.type «= pg. KEYUP:
if event.key == pg.K_RIGHT:
ship.moving right
= False

Pygame

aliens):


Collisions between two groups

score
event

if

if

if

collisions = pg.sprite.groupcollide(
bullets, aliens,
True, True)

Pygame groups
Ae - ei

The spritecoliideany()
function takes an object and a group, and

returns True il the object overaps with any member of the group.

The sprite.groupcoliide()
function takes two groups, and two
booleans. The function returns a dictionary containing information
about the members that have collided. The booleans tell Pygame
whether to delete the members of either group tha! have collided.


pe-mouse,set_visible(False)

Responding to key presses

Detecting collisions

The mouse position is returned as a tuple.

Hiding the mouse

Pygame’s main event loop registers a KEYDOWN event any time a
key is pressed. When this happens, you can check for specific

bullets.remove(bullet)

Finding the mouse position

leloe

ME

it's important to delete elements that will never appear again in the

documentation

bullets

=

new_bullet


Group({)

«

Bullet()

bullets.add(new

The sprites() method returns all the members

color

“Play

be color

of a group.

bullet
in bullets.sprites():
bullet.draw bullet()

Calling update() on a group

Calling update() on a group automatically calls update() on each
member of the group.
bullets.update()

«


msg

again?”
=

=

(100,

(236,

100,

230,

100)

230)

bullet)

Looping through the items in a group
for

msg

f = pg.font.SysFont(None, 48)
msg image = f.render(msg,
True, msg color,

bg color)
msg image rect = msg image.get rect()
msp image rect.center

screen.blit(msg

image,

=

screen_rect,.center

msg

image

rect)

More cheat sheets available at

ehmatthes.github.|o/pcc/


Beginners Python
Cheat Sheet —

matplotlib
What is matplotlib?
Data visualization involves exploring data through


visual representations. The matplotlib package helps
you make visually appealing representations of the

data you're working with. matplotlib is extremely
flexible; these examples will help you get started with
a few simple visualizations,

^

Customizing plots (cont.)

Making a scatter plot

Emphasizing points

The scatier() function takes a list of x values and a list of y values,
and a variety of optional arguments. The s=18 argument controls
the size of each point.
import

matplotlib.pyplot

Tỉ,

plt.scatter(x_values,
plt.show()

tlh

nn


be

install

python3-matplotlib

matplotlib.pyplot

Start a terminal session and enter isport matplotlib fo see #f
it's already installed on your system. If not, try this command:
pip

install

as

plt

--user

matplotlib

matplotlib on Windows

You first need to install Visual Studio, which you can do from
httpsv/dev.windows.cam/. The Community edition is free. Then go
fo https>/pypi.python.org/pypt'maiploltlib’ or
httÐ:/Awww. Wfđ uic. edu/~qohike/pythonilbs/#@maiplotlib and download


an appropriate installer file.

Numbers”,

fontsize=24)

6,

116e000))

5=16)

plt.title("Square

Numbers",

squares[-1],
s=100)

x_ values

matplotlib.pyplot

«

[@,

1,

2,


3,

as

4,

plt

5]

squares = [@, 1, 4, 9, 16, 25]
plit.plot(x_values,
squares)
pit.show()

c=‘red',

fontsize=24)

--snip--

each axis, and hide it.

plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)

Setting a custom figure size

You can make your plot as big or small

as you want. Before
plotting your data, add the following code. The dpi argument is
optional; if you don't know your system's resolution you cart omit
the argument and adjust the figsize argument accordingly.
figsize=(10,

6))

A colormap varies the point colors from one shade to another,
based on a certain value for each point. The vaive used to
determine the cotor 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
values,

squares,

c=squares,

edgecolor«‘none’,

The matp(otitb 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 tims extra whitespace from the plot.
plt.savefig(
' squares.png'ˆ;

Online

Bet:

"2n

bbox_inches='"tight')

resources
/'ociIin

AT

Making a line graph
import

c="green',

Saving a plot

Using a colormap

cmapeplt.cm.Blues,

Line graphs and scatter plots

plt

x values = list(range(100@))
squares = [x**2 for x in x_values]
plt.scatter(x_values,
squares,

c#squares,
cmap=plt.cm.Blues,
edgecolor='none’,

plt.figure(dpi=128,

pit.show()

s=19)

as

You can customize or remove axes entirely. Here's how to access

in x_values]
Squares,
$#10)

labelsize=14)

plt.scatter(x

matplotlib.pyplot

re-

Removing axes

l1ist(range(19096))


1108,

import

plt.scatter(x_values[-1],
edgecolor="none',

S/0/n

plit.axis([@,

You can piot as much data as you want on one plot. Here we
plot the first and last points larger fo emphasize them.

plt.scatter(x values[@],
squares[@],
edgecolor='none',
s=198)

plt.xlabel("“Value",
fontsize»18)
plt.ylabel("Square of Value”,
fontsize=18)
plt.tick_params(axis="both',
which="major',

matplotlib on OS X

$


s=10)

Adding titles and labels, and scaling axes

x values

matplotlib on Linux
apt-get

squares,

;
IV,

plt.title("Square

sudo

pit

Customizing plots

squares = [x**2 for x
plt.scatter(x_values,

$

as

x values = 1i1st(Frange(1988))

squares = [x**2 for x in x_values]

import

Installing matplotlib
fii}

Line graphs and scatter plots (cont.)

Python Crash Course
Covers Python 3 and Python 2
nostarchpress.com/pythoncrashcourse


Working with dates and times

Multipie plots


(cont.)

Muitiple
plots in one figure

Datetime formatting arguments

The strftime() function generates a formatted string from a

datetime object, and the strptime({) function


Plotting
two sets of data
import

matplotlib.pyplot

as plt

x_values = list(range(11))
squares = [x**2 for x in x_values]
cubes « [x**3 for x in x_values]
plt.scatter(x_values, squares, c='blue’,
edgecolor='none', s=20)
plt.scatter(x_values, cubes, c='red’,
edgecolor='none', s=20)
pit.axis([9,
plt. show( )

11,

9,

The fill_between() method fills the space between two data
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
argument that controls the color’s transparency.

plt.fill_between(x_values, cubes, squares,
facecolor='blue', alpha=@.25)


as dt
'Xm/Xd/XY')

You can also generate a datetime object for any date and time you
want. The positional order of arguments is year, month, and day.
The hour, minute, second, and microsecond arguments are
optional.
datetime

new_years » dt(2017, 1, 1)
fall_equinox = dt(year=2016,

import

datetime

month=9,

columns generated in the figure.

import

matplotlib.pyplot

as plt

x_vals = list(range(i1))
squares = [x**2 for x in x_vals]
cubes « [x**3 for x in x_vals]

fig,

axarr

= plt.subplots(2,

1,

axarr[1].scatter(x
vals, cubes,
axarr{[1].set_title(
'Cubes '}

as dt

To share a y-axis, we use the sharey*xTrue
argumeni.

import

matplotlib.pyplot

x_vals

= 1ist(range(11))

as plt

squares = [x**2 for x in x_vals]
cubes


« [x**3

x in x_vals]

axarr(@]).scatter(x_vals, squares)
axarr[@].set_title('Squares
'}

23),

dt(2016,

6,

24),

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

pÌt.. show( )

axarr

for


]

6,

c='red')

Sharing
a y-axis

fig,

dt(2016,

sharex=True)

axarr(@]).scatter(x_vals, squares)
axarr[@].set_title('Squares')

dt(2016, 6, 21), dt(2@16, 6, 22),

fig.autofmt_xdate()
day=22)

The following code plots a set of squares and a set of cubes on
two separate graphs that share a common x-axis.
The pit. subplots() function returns a figure object and a tuple
of axes. Each set of axes corresponds to a separate pilot in the
figure. The first two arguments control the number of rows and


pÌt. show( }

= [

)

as dt

%Y')

The following code creates a list of dates and a corresponding list
of high temperatures. It then plots the high temperatures, with the
date labels displayed in a specitic format.

highs = [57, 68, 64, 59]

Generating
a specific date

import

'%B %d,

Plotting
high temperatures

dates

today = dt.now()
date_string = dt.strftime(today,

print(date_string)

from datetime

‘Xm/%d/%Y')

import matplotlib.pyplot as plt
from matplotlib import dates as mdates

Generating
the current date

datetime

ny_string = dt.strftime(new_years,
print(ny_string)

from datetime

time:

The datetime.now() function returns a datetime
object
representing
the current date and time.
import

Converting
a string to a datetime object
Converting

a datetime object to a string

Filling the space between data sets

from datetime

such as Monday

« dt.strptime('1/1/2017',

frre:

Sharing
an x-axis

Month name, such as January
Month, as a number (@1 to 12)
Day of the month, as a number (@1 to 31)
Four-digit year, such as 2016
Two-digit year, such as 16
Hour, in 24-hour format (@@ to 23)
Hour, in 12-hour format (@1 to 12)
AM or PM
Minutes (@@ to 59)
Seconds (@@ to 61)

new_years

1190])


Working
with dates and

Weekday name,

ReSRESLEGES

Here we use plt.scatter() twice fo plot square numbers
and
cubes on the same figure.

Fe

a

= plt.subplots(1,

2,

axarr[1].scatter(x_vals, cubes,
axarr[1].set_title(
'Cubes ' )

sharey=True)

c='red')

pÌìt. show( }

%d %Y' })


More cheat sheets available at
ehmatthes.github.lo/pcc/



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×