Show Menu
Cheatography

Python basics Cheat Sheet (DRAFT) by

Basics commands for Python

This is a draft cheat sheet. It is a work in progress and is not finished yet.

OPERATIONS

espone­ntial
**
remainer
%
Parent­hesis have priority

STRINGS

quotes
'
double quotes
"
wrap quotes
" ' "

PRINT

# Normal print
print(var)

# Print formatting
print('My number is: {}, and my name is: {}'
.format(v1,v2)) # Print formatting 2
# (with order)
print('My number is: {one}, and my name is: {two}'.format(one=var1,two=var2))

VARIABLES NAMES RULES

. cannot start with numbers
. cannot start with special char
. underscore to chain_­words

VARIABLE TYPES

Lists
it uses [ ]
create
list = ['a','­b','c'] or
list = [1,2,3]
append
list.a­ppe­nd('d')
nested
nest = [1,2,3­,[4­,5,­['t­arg­et']]]
- indexing
nest[3­][2][0] = ''target'
Tuples
uses ( ) cannot change
create
t = (1,2,3)
Dictionaries
it uses { }
has keys and values
create
d = {
 'key1':'item1',
 'key2':'item2'}
indexing
d['key1'] = 'item1'
indexing 2
d[key1­][0:3] = 'ite'
Sets *
it uses { } has unique values
create
s = {1,2,2,2,2,3,3,3,4} = 1,2,3,4
append
s.add(5)
Booleans
True, False
sets differs from dictionary because has no keys and has unique values
 

INDEXING

s = 'hello'

# Indexing starts at 0
s[0]= 'h'
# the last value is excluded
s[0:2] = 'he'

LOOPS

if
if 1 < 2:
 ­pri­nt(­'Yep!')
if else
if 1 > 2:
  print('first')
else:
  print(­'last')
if elif
if 1 == 2:
  print('first')
elif 3 == 3:
  print('middle')
else:
  print(­'Last')
for
seq = [1,2,3,4,5]
for item in seq:
 print(item)
while
i = 1
while i < 5:
  print('i is: {}'.format(i))
  i = i+1
* elif: will execute only the first true condition
 

FUNCTIONS

range(num)
create range from 0 to x
list(r­ang­e(num))
convert range to list
list
comprehension
out = [var**2 for var in x]
functions *
def fun(param1='default'):
 print('Hello ' + param1)
return
return a value
print
print a value
lambda
expressions
*
lambda var: var*2
map *
map(fu­nct­ion­,seq)
filter *
filter­(fu­nct­ion­,seq)
In functions param1 defines the default parameter if there is no input.
lambda: take what: give what.
map: it applies a function to something. map(what, to_what). Also, the list is necessary to have the right output.
apply works on a row / column basis of a DataFrame, applymap works elemen­t-wise on a DataFrame, and map works elemen­t-wise on a Series.
filter: takes out only the results of a certain condition

METHODS

string.lo­wer()
'aaaa'
string.up­per()
'AAAA'
string.sp­lit() *
'ciao' 'sono' 'io'
s.split('symbol')
split using a symbol
dict.k­eys()
dict_keys(['key1', 'key2'])
dict.i­tems()
dict_items([('key1', 'item1')])
list.p­op(n)
take out the Ith element
var in [list]
check in a list - bool
split() supports also indexing after:
str.sp­lit­()[0]