Python Chee T Set
Python Chee T Set
Identifers
Conversions
…
→
→ nd
can speciy integer number base in 2 parameter
……ollowed by ………
◽ diacritics allowed but should be avoided → truncate decimal part
◽ language keywords orbidden →
◽ lower/UPPER case discrimination → rounding to 1 decimal (0 decimal → integer number)
or null , empty container , or ; or other
→ … representation string o or display
→ → code ↔ char
Variables assignment
→ …
representation string o
☝ assignment ⇔ binding o a with a
→
→
→
→
and
→
→
→ o
→
and
→
⇔
⇔ →
«»
sequence o one type → o another type
… →
… Sequence Containers Indexing
Items count Individual access to items via
→ → ⇒
→
→ ⇒
→
☝ index rom 0
(here rom 0 to 4)
Access to sub-sequences via
→ → → →
→ → → →
→ →
→
⁝ ☝ modules and packages searched in
(c )
logical or
Conditional Statement
…
☝ pitall :
⁝ yes no yes
? ?
⇒
no
logical not
Can go with several
,
... and only one
True and False constants ☝
nal
. Only the block o rst true
K
condition is executed.
☝
…
Maths ☝
:
⇔
Operators: …
⇔
Priority … × ÷ ab →…
integer ÷ ÷ remainder →… Exceptions on Errors
Signaling an error:
→ matrix ×
→√ C
…
→ → Errors processing:
→ → X
→ →
→ modules , , ,
☝
☝
, , ,
TYPE -1
Conditional Loop Statement
Iterative Loop Statement
yes next
Loop Control …
?
no nish
☝
A
:
s= ∑ i
☝
☝
A:
i=
Display loop on dict/set ⇔ loop on keys sequences
use
to loop on a subset o a sequence
→
☝
→
C /
y
☝ dont orget to close the fle ater use ! →
◽ Formatting :
write cache [ ]
resize
~
:
at start or lling with 0
→
[
] integer: binary, char, decimal (deault), octal, or hexa…
Very common: opening with a guarded block … oat: or exponential, or xed point, or appropriate (deault),
(automatic closing) and reading loop on lines string: … percent
o a text le:
◽ Conversion : (readable text) or (literal representation)
TYPE -2
Python Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/19/
Python sys Variables Python Class Special Methods Python String Methods (cont)
isspace() * swapcase() *
replace() utcoffset()
isoformat() dst()
__str__() tzname()
strftime(format)
%A Weekday (Sunday)
%p AM or PM
%w Weekday² (0 to 6)
%x Date
%X Time
%Y Year (2008)
Python
Cheat Sheet
Python 3 is a truly versatile prorammin lanuae, loved
both by web developers, data scientists and software
enineers. And there are several ood reasons for that!
• Python is open-source and has a reat support community,
• Plus, extensive support libraries.
• ts data structures are user-friendly.
Once you et a han of it, your development speed and productivity will soar!
ale of ontents
trins — codify a seuence of characters usin a strin. or example, the word
“hello”. n Python 3, strins are immutable. f you already dened one, you cannot
chane it later on.
hile you can modify a strin with commands such as replace or oin, they will
create a copy of a strin and apply modication to it, rather than rewrite the oriinal
one.
Plus, another three types worth mentionin are lists, dictionaries, and tuples. All of
them are discussed in the next sections.
or now, let’s focus on the strins.
! hichever option you choose, you should stic to it and use it consistently
within your proram.
As the next step, you can use the print function to output your strin in the console
window. his lets you review your code and ensure that all functions well.
ere’s a snippet for that
trin oncatenation
he next thin you can master is concatenation — a way to add two strins
toether usin the “” operator. ere’s how it’s done
ote ou can’t apply operator to two dierent data types e.. strin inteer. f
you try to do that, you’ll et the followin Python error
trin eplication
As the name implies, this command lets you repeat the same strin several times.
his is done usin operator. ind that this operator acts as a replicator only with
strin data types. hen applied to numbers, it acts as a multiplier.
trin replication example
‘lice’ ‘licelicelicelicelice’
rint“lice”
ath Operators
or reference, here’s a list of other math operations you can apply towards numbers
** Exponent 2 ** 3 = 8
% Modulus/Remainder 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4
ow when you print this out, you receive the strin output.
rintmy_str
ello orld
ee y usin variables, you save yourself heaps of eort as you don’t need to
retype the complete strin every time you want to use it.
nput unction
input function is a simple way to prompt the user for some input e.. provide their
name. All user input is stored as a strin.
ere’s a uic snippet to illustrate this
hen you run this short proram, the results will loo lie this
len unction
len function helps you nd the lenth of any strin, list, tuple, dictionary, or another
data type. t’s a handy command to determine excessive values and trim them to
optimie the performance of your proram.
ere’s an input function example for a strin
# testing len()
str = “oe you are enoying our tutorial!”
rint“he length of the string is ”, lenstr
utput
lter
se the ilter function to exclude items in an iterable obect lists, tuples,
dictionaries, etc
def myunc
if
return alse
else
return rue
for in adults
rint
ptional he P version of the checlist can also include a full table of all the in-built
functions.
def name
ext, you’ll need to add a second code line with a -space indent to specify what
this function should do.
def name
rint“hat’s your name”
namey
def name
rint“hat’s your name”
name()
hello
ow, let’s tae a loo at a dened function with a parameter — an entity, specifyin
an arument that a function can accept.
add_numbers, ,
n this case, you pass the number in for the x parameter, in for the y parameter,
and 3 in for the parameter. he proram will that do the simple math of addin up
the numbers
utput
a 3
4 3
c 5 3
utput
Product Name:
roductname White
hite T-Shirt
shirt
Price:
rice 5 15
Product Name:
roductname Jeans
eans
Price:
rice 4545
ists
ists are another cornerstone data type in Python used to specify an ordered
seuence of elements. n short, they help you eep related data toether and
perform the same operations on several values at once. nlie strins, lists are
mutable chaneable.
ach value inside a list is called an item and these are placed between suare
bracets.
ample lists
my_list = , ,
my_list = “a”, “b”, “c”
my_list = “”, d, “boo”,
he second option is to insert function to add an item at the specied index
econdly, you can use the pop function. f no index is specied, it will remove the
last item.
P.. ou can also apply del towards the entire list to scrap it.
my_list = , ,
my_list = “a”, “b”, “c”
combo_list = my_list my_list
combo_list
, , , ‘a’, ‘b’, ‘c’
ort a ist
se the sort function to oranie all items in your list.
lice a ist
ow, if you want to call ust a few elements from your list e.. the rst items,
you need to specify a rane of index numbers separated by a colon xy. ere’s an
example
alha_list
, , ,
utput
for in range,
beta_list = ‘fruit’
rintbeta_list
opy a ist
se the built-in copy function to replicate your data
ist omprehensions
ist comprehensions are a handy option for creatin lists based on existin lists.
hen usin them you can build by usin strins and tuples as well.
ere’s a more complex example that features math operators, inteers, and the
rane function
uples
uples are similar to lists — they allow you to display an ordered seuence of
elements. owever, they are immutable and you can’t chane the values stored in a
tuple.
he advantae of usin tuples over lists is that the former are slihtly faster. o it’s
a nice way to optimie your code.
ote nce you create a tuple, you can’t add new items to it or chane it in any other way!
utput
, 3, 5, 7,
ictionaries
A dictionary holds indexes with eys that are mapped to certain values. hese
ey-value pairs oer a reat way of oraniin and storin data in Python. hey are
mutable, meanin you can chane the stored information.
A ey value can be either a strin, oolean, or inteer. ere’s an example dictionary
illustratin this
And you can use the same two approaches to add values to your dictionary
ne_dict =
“brand” “onda”,
“model” “iic”,
“year”
}
rintne_dict
= ne_dict“brand”
ou can also use the followin methods to accomplish the same.
• dicteys isolates eys
• dictalues isolates values
• dictitems returns items in a list format of ey, value tuple pairs
ne_dict=
“brand” “onda”,
“model” “iic”,
“year”
}
ne_dict“year” =
ote n this case, the return values are the eys of the dictionary. ut, you can also return
values usin another method.
for in ne_dict
rint
for in ne_dict
rintne_dict
for , y in my_dictitems
rint, y
f tatements onditional
tatements in ython
ust lie other prorammin lanuaes, Python supports the basic loical
conditions from math
• uals a b
• ot uals a ! b
• ess than a b
• ess than or eual to a b
• reater than a b
• reater than or eual to a b
ou can leverae these conditions in various ways. ut most liely, you’ll use them in
“if statements” and loops
f tatement ample
he oal of a conditional statement is to chec if it’s rue or alse.
if
rint“hat’s rue!”
utput
hat’s rue!
ested f tatements
or more complex operations, you can create nested if statements. ere’s how it
loos
=
if
rint“boe tenty,”
if
rint“and also aboe !”
lif tatements
elif eyword prompts your proram to try another condition if the previous ones
was not true. ere’s an example
a =
b =
if b a
rint“b is greater than a”
elif a == b
rint“a and b are eual”
f lse tatements
else eyword helps you add some additional lters to your condition clause. ere’s
how an if-elif-else combo loos
if age
ticet_rice = 0
elif age
ticet_rice =
else ticet_rice =
fottatements
ot eyword let’s you chec for the opposite meanin to verify whether the value is
rue
ne_list = , , ,
=
if not in ne_list
rint“’’ isn’t on the list, so this is rue!”
ass tatements
f statements can’t be empty. ut if that’s your case, add the pass statement to avoid
havin an error
a =
b =
if b a
ass
ython oops
Python has two simple loop commands that are ood to now
• for loops
• while loops
or oop
As already illustrated in the other sections of this Python checlist, for loop is a
handy way for iteratin over a seuence such as a list, tuple, dictionary, strin, etc.
ere’s an example showin how to loop throuh a strin
for in “ale”
rint
Plus, you’ve already seen other examples for lists and dictionaries.
hile oops
hile loop enables you to execute a set of statements as lon as the condition for
them is true.
i =
hile i
rint
i =
i =
hile i
rinti
if i ==
brea
i =
lass
ince Python is an obect-oriented prorammin lanuae almost every element of
it is an oect — with its methods and properties.
lass acts as a blueprint for creatin dierent obects. Oects are an instance of a
class, where the class is manifested in some proram.
class estlass
=
= estlass
rint
urther, you can assin dierent attributes and methods to your obect. he
example is below
class carobect
“””docstring”””
def braeself
“””
to the car
“””
return “raing”
def drieself
“””
rie the car
“””
return “I’m driing!”
class arehicle
“””
he ar class
“””
def braeself
“””
erride brae method
“””
return “he car class is breaing sloly!”
if __name__ == “__main__”
car = ar“yello”, , , “car”
carbrae
‘he car class is breaing sloly!’
cardrie
“I’m driing a yello car!”
ou can also detect several exceptions at once with a sinle statement. ere’s an
example for that
try
alue = my_dict“a”
ecet eyrror
rint“ eyrror occurred!”
else
rint“o error occurred!”
onclusions
ow you now the core ython concepts!
y no means is this Python checlist comprehensive. ut it includes all the ey data
types, functions and commands you should learn as a beinner.
As always, we welcome your feedback in the comment section below!