Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

TYPE -1

©2012-2015 - Laurent Pointal Mémento v2.0.6


License Creative Commons Attribution 4 Python 3 Cheat Sheet 






:




















:







:
















 Base Types ◾ ordered sequences, ast index access, repeatable values Container Types
          

 

 
 
     
  
-6 








 ☝ 








→
  ×10

   











   




: 





  ◾ key containers, no 



order,
ast key access, each key is unique
  dictionary    


 



 








π
 collection    




 ☝


 ☝

=












… 




 









 Identifers  
 
  Conversions




…
 
→
→ nd
can speciy 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 











→ → → →
→ → → →
→ →
















→






 






















Boolean Logic Statements Blocks 




⇔

. Modules/Names Imports
Comparisons :       




   = ≠ 



 →













 logical and 




 


… →




.1

indentation !




 ⁝ ☝ modules and packages searched in 


(c )
 logical or 



 



 











 Conditional Statement


 


… 
 




☝ pitall :






 ⁝ 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






  



 





 







Go over sequence's values


 










 ☝ 





 


  

















 












A
:
 

☝ good habit : don't modiy loop variable


    i= 
 
 
 

 
 y
 


s= ∑ i 
☝

 
 ☝ 








  A:


 i=   



 




  Display loop on dict/set ⇔ loop on keys sequences
use 
to loop on a subset o a sequence

items to display : literal values, variables, expressions Go over sequence's index


options: ◽ modiy item at index
◽  items separator, deault space ◽ access items around index (beore / ater)

◽  end o print, deault new line 
◽  print to le, deault standard output  A
:




 


 


 Input
 





☝ always returns a string, convert it to required type 
(c. boxed C

 on the other side). 

→ items count Generic Operations on Containers Go simultaneously over sequence's index and values:
  :
 

 





 
→ sorted     
 
 
y

→ boolean, membership operator (absence ) [  
]
 [ 
 ] Integer Sequences
→  
on (index, value) ☝
deault 0, 
not included in sequence, 
signed, deault 1
…→  

 
on tuples containing items at same index
→ 0 1 2 3 4 → 2 5 8 11
→ i all items evaluated to true, else  → 3 4 5 6 7 → 20 15 10
→ i at least one item o evaluated true, else   → 

 


S





  
 


 







… ☝






















→ 
 

 → duplicate → concatenate
  
→ 

  
→ 



 unction name (identier) Function Defnition
 named parameters
→ shallow copy o container 
→ deep copy o container 

☝ modiy original list Operations on Lists #








       

 add item at end  result value o the call, i no computed
result to return: 

 add sequence o items at end ☝ parameters and all


 insert item at index variables o this block exist only the block and  

the unction

 remove rst item with value   call (think o a “black box” )
[
]
→ 
 remove & return item at index 
(deault last) Advanced: 
 sort / reverse liste  
  
 
 

  
 
 → 


 

  
 
 
   
   
→
Operations on Dictionaries Operations on Sets

  Operators:  Function Call
→ union (vertical bar char) 




 






→  
 → intersection 



 


 update/add → diference/symmetric dif. ☝ this is the use o unction  
associations A
:
 → inclusion relations name   
 


 → 
   
 


  which does the call 

  
 



[

]→   

 
  
[

[
]] Operations on Strings
→ 
  
[

]→      [

[
]][ ]


[



]→

  [
 
[
]] →




[
 
[
]] [

[
]]















 Files …







.()
 
[ 

]
le variable name o le
opening mode encoding o [
 ]
[ 

][ 
]
or operations on disk ◽ read chars or 
  [ 
] 

(+path…) ◽ write :
◽ append 8 acii ormating directives values to ormat Formatting
c. modules , and ◽ … lain1 …
 
writing ☝







 reading 










 [
] →




◽ Selection :






 

 
 

 
[ ]  →  



  →
Examples

 →


  
☝

 
 
 
 
 
 
 
 

  →
 
 
 
C /   
y 
 ☝ dont orget to close the fle ater use ! →
◽ Formatting :
write cache [  ]
 resize 
 
 








~














 
 

  :
  
 at start or lling with 0
→


 


[


] integer: binary, char, decimal (deault), octal, or hexa…
Very common: opening with a guarded block … oat: or exponential, or xed point, or appropriate (deault),
(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)

argv Command line args __new__(cls) __lt__(self, other) istitle() * title() *

builtin_module_‐ Linked C modules __init__(self, args) __le__(self, other) isupper() * translate(table)


names __del__(self) __gt__(self, other) join() upper() *
byteorder Native byte order __repr__(self) __ge__(self, other) ljust(width) zfill(width)
check_interval Signal check __str__(self) __eq__(self, other) lower() *
frequency
__cmp__(self, other) __ne__(self, other) Methods marked * are locale dependant for
exec_prefix Root directory
__index__(self) __nonzero__(self) 8-bit strings.
executable Name of executable
__hash__(self)
exitfunc Exit function name Python File Methods
__getattr__(self, name)
modules Loaded modules close() readlines(size)
__getattribute__(self, name)
path Search path flush() seek(offset)
__setattr__(self, name, attr)
platform Current platform fileno() tell()
__delattr__(self, name)
stdin, stdout, stderr File objects for I/O isatty() truncate(size)
__call__(self, args, kwargs)
version_info Python version info next() write(string)

winver Version number Python List Methods read(size) writelines(list)

append(item) pop(position) readline(size)


Python sys.argv
count(item) remove(item)
sys.argv[0] foo.py Python Indexes and Slices
extend(list) reverse()
sys.argv[1] bar len(a) 6
index(item) sort()
sys.argv[2] -c a[0] 0
insert(position, item)
sys.argv[3] qux a[5] 5

sys.argv[4] --h Python String Methods a[-1] 5

sys.argv for the command: capitalize() * lstrip() a[-2] 4


$ python foo.py bar -c qux --h center(width) partition(sep) a[1:] [1,2,3,4,5]

count(sub, start, replace(old, new) a[:5] [0,1,2,3,4]


Python os Variables
end) a[:-2] [0,1,2,3]
altsep Alternative sep
decode() rfind(sub, start ,end) a[1:3] [1,2]
curdir Current dir string
encode() rindex(sub, start, a[1:-1] [1,2,3,4]
defpath Default search path end)
b=a[:] Shallow copy of a
devnull Path of null device endswith(sub) rjust(width)
Indexes and Slices of a=[0,1,2,3,4,5]
extsep Extension separator expandtabs() rpartition(sep)
linesep Line separator find(sub, start, end) rsplit(sep) Python Datetime Methods
name Name of OS index(sub, start, rstrip() today() fromordinal(ordinal)
pardir Parent dir string end)
now(timezoneinfo) combine(date, time)
pathsep Patch separator isalnum() * split(sep)
utcnow() strptime(date, format)
sep Path separator isalpha() * splitlines()
fromtimestamp(timestamp)
Registered OS names: "posix", "nt", isdigit() * startswith(sub)
utcfromtimestamp(timestamp)
"mac", "os2", "ce", "java", "riscos" islower() * strip()

isspace() * swapcase() *

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by ApolloPad.com


cheatography.com/davechild/ Last updated 3rd November, 2020. Everyone has a novel in them. Finish
aloneonahill.com Page 1 of 2. Yours!
https://apollopad.com
TYPE -2
Python Cheat Sheet
by Dave Child (DaveChild) via cheatography.com/1/cs/19/

Python Time Methods

replace() utcoffset()

isoformat() dst()

__str__() tzname()

strftime(format)

Python Date Formatting

%a Abbreviated weekday (Sun)

%A Weekday (Sunday)

%b Abbreviated month name (Jan)

%B Month name (January)

%c Date and time

%d Day (leading zeros) (01 to 31)

%H 24 hour (leading zeros) (00 to 23)

%I 12 hour (leading zeros) (01 to 12)

%j Day of year (001 to 366)

%m Month (01 to 12)

%M Minute (00 to 59)

%p AM or PM

%S Second (00 to 61⁴)

%U Week number¹ (00 to 53)

%w Weekday² (0 to 6)

%W Week number³ (00 to 53)

%x Date

%X Time

%y Year without century (00 to 99)

%Y Year (2008)

%Z Time zone (GMT)

%% A literal "%" character (%)

¹ Sunday as start of week. All days in a new


year preceding the first Sunday are
considered to be in week 0.
² 0 is Sunday, 6 is Saturday.
³ Monday as start of week. All days in a new
year preceding the first Monday are
considered to be in week 0.
⁴ This is not a mistake. Range takes
account of leap and double-leap seconds.

By Dave Child (DaveChild) Published 19th October, 2011. Sponsored by ApolloPad.com


cheatography.com/davechild/ Last updated 3rd November, 2020. Everyone has a novel in them. Finish
aloneonahill.com Page 2 of 2. Yours!
https://apollopad.com
Lists Also see NumPy Arrays Libraries
Python For Data Science Cheat Sheet >>> a = 'is'
TYPE -3 Import libraries
Python Basics >>> b = 'nice' >>> import numpy Data analysis Machine learning
Learn More Python for Data Science Interactively at www.datacamp.com >>> my_list = ['my', 'list', a, b] >>> import numpy as np
>>> my_list2 = [[4,5,6,7], [3,4,5,6]] Selective import
>>> from math import pi Scientic computing 2D ploing
Variables and Data Types Selecting List Elements Index starts at 0
Subset Install Python
Variable Assignment
>>> my_list[1] Select item at index 1
>>> x=5
>>> my_list[-3] Select 3rd last item
>>> x
Slice
5 Select items at index 1 and 2
>>> my_list[1:3]
Calculations With Variables >>> my_list[1:] Select items aer index 0
>>> my_list[:3] Select items before index 3 Leading open data science platform Free IDE that is included Create and share
>>> x+2 Sum of two variables powered by Python with Anaconda documents with live code,
>>> my_list[:] Copy my_list
7 visualizations, text, ...
>>> x-2 Subtraction of two variables
Subset Lists of Lists
>>> my_list2[1][0] my_list[list][itemOfList]
3 Numpy Arrays Also see Lists
>>> my_list2[1][:2]
>>> x*2 Multiplication of two variables
>>> my_list = [1, 2, 3, 4]
10 List Operations
>>> x**2 Exponentiation of a variable >>> my_array = np.array(my_list)
25 >>> my_list + my_list >>> my_2darray = np.array([[1,2,3],[4,5,6]])
>>> x%2 Remainder of a variable ['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
Selecting Numpy Array Elements Index starts at 0
1 >>> my_list * 2
>>> x/foat(2) Division of a variable ['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice'] Subset
2.5 >>> my_list2 > 4 >>> my_array[1] Select item at index 1
True 2
Types and Type Conversion Slice
List Methods >>> my_array[0:2] Select items at index 0 and 1
str() '5', '3.45', 'True' Variables to strings
my_list.index(a) Get the index of an item array([1, 2])
>>>
int() 5, 3, 1 Variables to integers >>> my_list.count(a) Count an item Subset 2D Numpy arrays
>>> my_list.append('!') Append an item at a time >>> my_2darray[:,0] my_2darray[rows, columns]
my_list.remove('!') Remove an item array([1, 4])
foat() 5.0, 1.0 Variables to oats >>>
>>> del(my_list[0:1]) Remove an item Numpy Array Operations
bool() True, True, True Variables to booleans >>> my_list.reverse() Reverse the list
>>> my_array > 3
>>> my_list.extend('!') Append an item array([False, False, False, True], dtype=bool)
>>> my_list.pop(-1) Remove an item >>> my_array * 2
Asking For Help >>> my_list.insert(0,'!') Insert an item array([2, 4, 6, 8])
>>> help(str) >>> my_list.sort() Sort the list >>> my_array + np.array([5, 6, 7, 8])
array([6, 8, 10, 12])
Strings
>>> my_string = 'thisStringIsAwesome' Numpy Array Functions
String Operations Index starts at 0
>>> my_string >>> my_array.shape Get the dimensions of the array
'thisStringIsAwesome' >>> my_string[3] >>> np.append(other_array) Append items to an array
>>> my_string[4:9] >>> np.insert(my_array, 1, 5) Insert items in an array
String Operations >>> np.delete(my_array,[1]) Delete items in an array
String Methods >>> np.mean(my_array) Mean of the array
>>> my_string * 2
'thisStringIsAwesomethisStringIsAwesome' >>> my_string.upper() String to uppercase >>> np.median(my_array) Median of the array
>>> my_string + 'Innit' >>> my_string.lower() String to lowercase >>> my_array.corrcoef() Correlation coecient
'thisStringIsAwesomeInnit' >>> my_string.count('w') Count String elements >>> np.std(my_array) Standard deviation
>>> 'm' in my_string >>> my_string.replace('e', 'i') Replace String elements
True >>> my_string.strip() Strip whitespaces DataCamp
Learn Python for Data Science Interactively
TYPE -4

Python
Cheat Sheet
Python 3 is a truly versatile prorammin lanuae, loved
both by web developers, data scientists and software
enineers. 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!
ale of ontents

03 Python asics ettin tarted


04 ain Python ata ypes
05 ow to reate a trin in Python
06 ath perators
07 ow to tore trins in ariables
08 uilt-in unctions in Python
0 ow to ene a unction
 ist
6 ist omprehensions
6 uples
7 ictionaries
 f tatements onditional tatements in Python
 Python oops
 lass
3 ealin with Python xceptions rrors
4 ow to roubleshoot the rrors
5 onclusion
Python Cheat Sheet 3

ython asics ettin tarted


ost indows and ac computers come with Python pre-installed. ou can chec
that via a ommand ine search. he particular appeal of Python is that you can
write a proram in any text editor, save it in .py format and then run via a ommand
ine. ut as you learn to write more complex code or venture into data science, you
miht want to switch to an  or .

hat is  nterated evelopment and earnin


 nterated evelopment and earnin nvironment comes with every
Python installation. ts advantae over other text editors is that it hihlihts
important eywords e.. strin functions, main it easier for you to interpret code.
hell is the default mode of operation for Python . n essence, it’s a simple loop
that performs that followin four steps
• eads the Python statement
• valuates the results of it
• Prints the result on the screen
• And then loops bac to read the next statement.

Python shell is a reat place to test various small code snippets.

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ain ython ata ypes


very value in Python is called an “oect”. And every obect has a specic data
type. he three most-used data types are as follows
nteers int — an inteer number to represent an obect such as “number 3”.
Integers -2, -1, 0, 1, 2, 3, 4, 5

loatinpoint numers oat — use them to represent oatin-point numbers.


Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25

trins — codify a seuence of characters usin a strin. or example, the word
“hello”. n Python 3, strins are immutable. f you already dened one, you cannot
chane 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 modication to it, rather than rewrite the oriinal
one.

Strings ‘yo’, ‘hey’, ‘Hello!’, ‘what’s up!’

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 strins.

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ow to reate a trin in ython


ou can create a strin in three ways usin sinle, doule or triple uotes. ere’s an
example of every option

asic ython trin

my_string = “Let’s Learn Python!”


another_string = ‘It may seem difficult first, but you
can do it!’
a_long_string = ‘’’Yes, you can een master multiline
strings
that coer more than one line
ith some ractice’’’

! hichever option you choose, you should stic to it and use it consistently
within your proram.
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

rint“Let’s rint out a string!”

trin oncatenation
he next thin you can master is concatenation — a way to add two strins
toether usin the “” operator. ere’s how it’s done

string_one = “I’m reading “


string_to = “a ne great boo!”
string_three = string_one  string_to

ote ou can’t apply  operator to two dierent data types e.. strin  inteer. f
you try to do that, you’ll et the followin Python error

yerror an’t conert ‘int’ obect to str imlicitly

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

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’   ‘licelicelicelicelice’

And with print 

rint“lice”  

And your output will be Alice written ve times in a row.

ath Operators
or reference, here’s a list of other math operations you can apply towards numbers

Operators Operation Example

** 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

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ow to tore trins in ariales


ariales in Python 3 are special symbols that assin a specic storae location to
a value that’s tied to it. n essence, variables are lie special labels that you place on
some value to now where it’s stored.
trins incorporate data. o you can “pac” them inside a variable. oin so maes
it easier to wor with complex Python prorams.
ere’s how you can store a strin inside a variable.

my_str = “ello orld”

et’s brea it down a bit further


• mystr is the variable name.
•  is the assinment operator.
• “ust a random strin” is a value you tie to the variable name.

ow when you print this out, you receive the strin output.

rintmy_str

 ello orld

ee y usin variables, you save yourself heaps of eort as you don’t need to
retype the complete strin every time you want to use it.

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

uiltin unctions in ython


ou already now the most popular function in Python — print. ow let’s tae a
loo at its eually popular cousins that are in-built in the platform.

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

name = inut“i! hat’s your name “


rint“ice to meet you “  name  “!”

age = inut“o old are you “


rint“o, you are already “  strage  “ years old, “
 name  “!”

hen you run this short proram, the results will loo lie this

i! hat’s your name “im”


ice to meet you, im!
ow old are you 5
o, you are already 5 years old, im!

len unction
len function helps you nd the lenth of any strin, list, tuple, dictionary, or another
data type. t’s a handy command to determine excessive values and trim them to
optimie the performance of your proram.
ere’s an input function example for a strin

# testing len()
str = “oe you are enoying our tutorial!”
rint“he length of the string is ”, lenstr

utput

he lenth of the strin is 35

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

lter
se the ilter function to exclude items in an iterable obect lists, tuples,
dictionaries, etc

ages = , , , , , 

def myunc
if   
return alse
else
return rue

adults = filtermyunc, ages

for  in adults
rint

ptional he P version of the checlist can also include a full table of all the in-built
functions.

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ow to ene a unction


Apart from usin in-built functions, Python 3 also allows you to dene your own
functions for your proram.
o recap, a function is a bloc of coded instructions that perform a certain action.
nce properly dened, a function can be reused throuhout your proram i.e. re-use
the same code.
ere’s a uic walthrouh explainin how to dene a function in Python
irst, use def eyword followed by the function name. he parentheses can
contain any parameters that your function should tae or stay empty.

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”

ow, you have to call this function to run the code.

namey
def name
rint“hat’s your name”

name()
hello

ow, let’s tae a loo at a dened function with a parameter — an entity, specifyin
an arument that a function can accept.

def add_numbers, y, 


a =   y
b =   
c = y  
rinta, b, c

add_numbers, , 

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

n this case, you pass the number  in for the x parameter,  in for the y parameter,
and 3 in for the  parameter. he proram will that do the simple math of addin up
the numbers
utput

a  3 
  4  3
c  5  3

ow to ass eyword ruments to a unction


A function can also accept eyword aruments. n this case, you can use
parameters in random order as the Python interpreter will use the provided
eywords to match the values to the parameters.
ere’s a simple example of how you pass a eyword arument to a function.

# Define function with


with parameters
parameters
def product_info (product name,
def roduct_inforoduct name, rice
price):
print(”Product Name: “ + product_name)
rint“roductname “  roduct name
print(”Price:““+strdollars
rint“Price str(price))

# Call function with parameters


parameters assigned
assigned as
as above
above
product_info(”White shirt”,
roduct_info“hite T-Shirt: “,
 15)
dollars

# Call function with keyword


keyword arguments
arguments
product_info(productname=”Jeans“, price=45)
roduct_inforoductname=”eans”, rice=

utput

Product Name:
roductname White
hite T-Shirt
shirt
Price:
rice 5 15
Product Name:
roductname Jeans
eans
Price:
rice 4545

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ists
ists are another cornerstone data type in Python used to specify an ordered
seuence of elements. n short, they help you eep related data toether and
perform the same operations on several values at once. nlie strins, lists are
mutable chaneable.
ach value inside a list is called an item and these are placed between suare
bracets.

ample lists
my_list = , , 
my_list = “a”, “b”, “c”
my_list = “”, d, “boo”, 

Alternatively, you can use list function to do the same

alha_list = list“”, “”, “”


rintalha_list

ow to dd tems to a ist


ou have two ways to add new items to existin lists.

he rst one is usin append function

beta_list = “ale”, “banana”, “orange”


beta_listaend“grae”
rintbeta_list

he second option is to insert function to add an item at the specied index

beta_list = “ale”, “banana”, “orange”


2,“grape”
beta_listinsert“ grae”
rintbeta_list

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 3

ow to emove an tem from a ist


Aain, you have several ways to do so. irst, you can use remove function

beta_list = “ale”, “banana”, “orange”


beta_listremoe“ale”
rintbeta_list

econdly, you can use the pop function. f no index is specied, it will remove the
last item.

beta_list = “ale”, “banana”, “orange”


beta_listo
rintbeta_list

he last option is to use del eyword to remove a specic item

beta_list = “ale”, “banana”, “orange”


del beta_list 
rintbeta_list

P.. ou can also apply del towards the entire list to scrap it.

omine wo ists


o mash up two lists use the  operator.

my_list = , , 
my_list = “a”, “b”, “c”
combo_list = my_list  my_list
combo_list
, , , ‘a’, ‘b’, ‘c’

reate a ested ist


ou can also create a list of your lists when you have plenty of them 

my_nested_list = my_list, my_list


my_nested_list
, , , ‘a’, ‘b’, ‘c’

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ort a ist
se the sort function to oranie all items in your list.

alha_list = , , , , , 


alha_listsort
alha_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 rane of index numbers separated by a colon xy. ere’s an
example

alha_list
, , , 

hane tem alue on our ist


ou can easily overwrite a value of one list items

beta_list = “ale”, “banana”, “orange”


beta_list = “ear”
rintbeta_list

utput

‘apple’, ‘pear’, ‘cherry’

oop hrouh the ist


sin for loop you can multiply the usae of certain items, similarly to what 
operator does. ere’s an example

for  in range,
beta_list = ‘fruit’
rintbeta_list

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

opy a ist
se the built-in copy function to replicate your data

beta_list = “ale”, “banana”, “orange”


beta_list = beta_listcoy
rintbeta_list

Alternatively, you can copy a list with the list method

beta_list = “ale”, “banana”, “orange”


beta_list = list beta_list
rintbeta_list

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ist omprehensions
ist comprehensions are a handy option for creatin lists based on existin lists.
hen usin them you can build by usin strins and tuples as well.

ist comprehensions eamples


list_ariable =  for  in iterable

ere’s a more complex example that features math operators, inteers, and the
rane function

number_list =    for  in range if    == 


rintnumber_list

uples
uples are similar to lists — they allow you to display an ordered seuence of
elements. owever, they are immutable and you can’t chane the values stored in a
tuple.
he advantae of usin tuples over lists is that the former are slihtly faster. o it’s
a nice way to optimie your code.

ow to reate a uple


my_tule = , , , , 
my_tule
, , 

ote nce you create a tuple, you can’t add new items to it or chane it in any other way!

ow to lide a uple


he process is similar to slicin lists.

numbers = , , , , , , , , , , , , 


rintnumbers

utput

, 3, 5, 7, 

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

onvert uple to a ist


ince uples are immutable, you can’t chane them. hat you can do thouh is
convert a tuple into a list, mae an edit and then convert it bac to a tuple.
ere’s how to accomplish this

 = “ale”, “orange”, “ear”


y = list
y = “grae”
 = tuley
rint

ictionaries
A dictionary holds indexes with eys that are mapped to certain values. hese
ey-value pairs oer a reat way of oraniin and storin data in Python. hey are
mutable, meanin you can chane the stored information.
A ey value can be either a strin, oolean, or inteer. ere’s an example dictionary
illustratin this

ustomer = ‘username’ ‘ohnsea’, ‘online’ false,


‘friends’}

ow to reate a ython ictionary


ere’s a uic example showcasin how to mae an empty dictionary.
ption  ne_dict = 
ption  other_dict= dict

And you can use the same two approaches to add values to your dictionary

ne_dict = 
“brand” “onda”,
“model” “iic”,
“year” 
}
rintne_dict

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ow to ccess a alue in a ictionary


ou can access any of the values in your dictionary the followin way

 = ne_dict“brand”

ou can also use the followin methods to accomplish the same.
• dicteys isolates eys
• dictalues isolates values
• dictitems returns items in a list format of ey, value tuple pairs

hane tem alue


o chane one of the items, you need to refer to it by its ey name

#Change the “year” to 2020:

ne_dict= 
“brand” “onda”,
“model” “iic”,
“year” 
}
ne_dict“year” = 

oop hrouh the ictionary


Aain to implement loopin, use for loop command.

ote n this case, the return values are the eys of the dictionary. ut, you can also return
values usin another method.

#print all key names in the dictionary

for  in ne_dict
rint

#print all values in the dictionary

for  in ne_dict
rintne_dict

#loop through both keys and values

for , y in my_dictitems
rint, y

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

f tatements onditional
tatements in ython
ust lie other prorammin lanuaes, Python supports the basic loical
conditions from math
• uals a  b
• ot uals a ! b
• ess than a  b
• ess than or eual to a  b
• reater than a  b
• reater than or eual to a  b
ou can leverae these conditions in various ways. ut most liely, 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
loos

 = 

if   
rint“boe tenty,”
if   
rint“and also aboe !”

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

lif tatements
elif eyword prompts your proram to try another condition if the previous ones
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 eual”

f lse tatements
else eyword helps you add some additional lters to your condition clause. ere’s
how an if-elif-else combo loos

if age  
ticet_rice = 0
elif age  
ticet_rice = 
else ticet_rice = 

fottatements
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

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

ython oops
Python has two simple loop commands that are ood to now
• for loops
• while loops

et’s tae a loo at each of these.

or oop
As already illustrated in the other sections of this Python checlist, for loop is a
handy way for iteratin over a seuence such as a list, tuple, dictionary, strin, etc.
ere’s an example showin how to loop throuh a strin

for  in “ale”
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.

#print as long as x is less than 8

i = 
hile i 
rint
i = 

ow to rea a oop


ou can also stop the loop from runnin even if the condition is met. or that, use
the brea statement both in while and for loops

i = 
hile i  
rinti
if i == 
brea
i = 

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

lass
ince Python is an obect-oriented prorammin lanuae almost every element of
it is an oect — with its methods and properties.
lass acts as a blueprint for creatin dierent obects. Oects are an instance of a
class, where the class is manifested in some proram.

ow to reate a lass


et’s create a class named estlass, with one property named 

class estlass
 = 

ow o reate an Oect


As a next step, you can create an obect usin your class. ere’s how it’s done

 = estlass
rint

urther, you can assin dierent attributes and methods to your obect. he
example is below

class carobect
“””docstring”””

def __init__self, color, doors, tires


“””onstructor”””
selfcolor = color
selfdoors = doors
selftires = tires

def braeself
“””
to the car
“””
return “raing”

def drieself
“””
rie the car
“””
return “I’m driing!”

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 3

ow to reate a uclass


very obect can be further sub-classied. ere’s an example

class arehicle
“””
he ar class
“””

def braeself
“””
erride brae method
“””
return “he car class is breaing sloly!”

if __name__ == “__main__”
car = ar“yello”, , , “car”
carbrae
‘he car class is breaing sloly!’
cardrie
“I’m driing a yello car!”

ealin with ython ceptions rrors


Python has a list of in-built exceptions errors that will pop up whenever you mae
a mistae in your code. As a newbie, it’s ood to now how to x these.

he ost ommon ython ceptions


• AttributeError — pops up when an attribute reference or assinment fails.
• IOError — emeres when some  operation e.. an open() function fails
for an -related reason, e.., “le not found” or “dis full”.
• ImportError — comes up when an import statement cannot locate the
module denition. Also, when a from… import can’t nd a name that must be
imported.
• IndexError — emeres when a seuence subscript is out of rane.
• KeyError — raised when a dictionary ey isn’t found in the set of existin eys.
• KeyboardInterrupt — lihts up when the user hits the interrupt ey such
as ontrol- or elete.
• NameError — shows up when a local or lobal name can’t be found.

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

• OSError — indicated a system-related error.


• SyntaxError — pops up when a parser encounters a syntax error.
• TypeError — comes up when an operation or function is applied to an obect
of inappropriate type.
• ValueError — raised when a built-in operationfunction ets an arument
that has the riht type but not an appropriate value, and the situation is not
described by a more precise exception such as ndexrror.
• ZeroDiviionError — emeres when the second arument of a division or
modulo operation is ero.

ow to rouleshoot the rrors


Python has a useful statement, desin ust for the purpose of handlin exceptions —
tryecept statement. ere’s a code snippet showin how you can catch eyrrors
in a dictionary usin this statement

my_dict = “a”, “b”, “c”}


try
alue = my_dict“d”
ecet eyrror
rint“hat ey does not eist!”

ou can also detect several exceptions at once with a sinle statement. ere’s an
example for that

my_dict = “a”, “b”, “c”}


try
alue = my_dict“d”
ecet Inderror
rint“his inde does not eist!”
ecet eyrror
rint“his ey is not in the dictionary!”
ecet
rint“ome other roblem haened!”

WebsiteSetup.or - Python Cheat Sheet


Python Cheat Sheet 

tryecept with else clause


Addin an ele laue ill elp you onirm tat no error
ere ound

my_dict = “a”, “b”, “c”}

try
alue = my_dict“a”
ecet eyrror
rint“ eyrror occurred!”
else
rint“o error occurred!”

onclusions
ow you now the core ython concepts!
y no means is this Python checlist comprehensive. ut it includes all the ey data
types, functions and commands you should learn as a beinner.
As always, we welcome your feedback in the comment section below!

WebsiteSetup.or - Python Cheat Sheet

You might also like