Basic Python

Variable asignment

In [1]:
name_of_var = 2 #can't have spaces or start with a number or special character
In [2]:
name_of_var #call for the variable
Out[2]:
2
In [3]:
print(name_of_var) #print values
2

Data types

In [4]:
num = 50
type(num) #integer
Out[4]:
int
In [5]:
num1 = 4.75
type(num1) #float
Out[5]:
float
In [6]:
cn = complex(3,4)
type(cn) #complex number
Out[6]:
complex
In [7]:
st = 'hola!'
type(st) #string
Out[7]:
str
In [8]:
boo = True
type(boo) #boolean
Out[8]:
bool
In [9]:
lst = [1,2,3]
type(lst) #list
Out[9]:
list
In [10]:
d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
type(d) #dictionary
Out[10]:
dict
In [11]:
t = (1,2,3)
type(t) #tuple
Out[11]:
tuple
In [12]:
s = {1,2,3}
type(s) #set
Out[12]:
set
In [13]:
fnc = lambda var: var*2
type(fnc) #function
Out[13]:
function

Change type

In [14]:
str(num) #number to string
Out[14]:
'50'
In [15]:
int(num1) #float to the nearest integer
Out[15]:
4
In [16]:
float(num) #integer to float
Out[16]:
50.0
In [17]:
bool(0) #False
bool(1) #True
Out[17]:
True
In [18]:
list(t) #tuple to list
Out[18]:
[1, 2, 3]
In [19]:
tuple(lst) #list to tuple
Out[19]:
(1, 2, 3)
In [20]:
list(d) #dictionaty to list (only keys)
Out[20]:
['key1', 'key2', 'key3']

Numbers

In [21]:
1 + 1 #sum
Out[21]:
2
In [22]:
5 - 2 #sustraction
Out[22]:
3
In [23]:
3 * 4 #product
Out[23]:
12
In [24]:
8 / 2 #division
Out[24]:
4.0
In [25]:
9 % 2 #module
Out[25]:
1
In [26]:
2 ** 3 #power
Out[26]:
8
In [27]:
x = 3
y = 6

res = (x * y) - (x + y)
res
Out[27]:
9
In [28]:
(2 + 3) * (5 + 5) #combinated operations
Out[28]:
50

Strings

In [29]:
st1 = 'single quotes'
st1
Out[29]:
'single quotes'
In [30]:
st2 = "double quotes"
st2
Out[30]:
'double quotes'
In [31]:
st1 + ' or ' + st2 #concatenate strings
Out[31]:
'single quotes or double quotes'
In [32]:
#assign variables
name = 'Paul'
num = 28

#include variables in text
print('My name is {one}, and my age is {two}'.format(one=name,two=num))
print('My name is {}, and my age is {}'.format(name,num))
My name is Paul, and my age is 28
My name is Paul, and my age is 28

Lists

In [33]:
[1,2,3] #same data type
Out[33]:
[1, 2, 3]
In [34]:
['hi',1,[1,2]] #different type
Out[34]:
['hi', 1, [1, 2]]
In [35]:
my_list = ['a','b','c']
my_list.append('d') #add value
my_list
Out[35]:
['a', 'b', 'c', 'd']

Dictionaties

In [36]:
d = {'key1':'value1','key2':'value2','key3':'value3'}
d
Out[36]:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Booleans

In [37]:
True & True #& means AND
Out[37]:
True
In [38]:
True & False
Out[38]:
False
In [39]:
False & False
Out[39]:
False
In [40]:
True | True #& means OR
Out[40]:
True
In [41]:
True | False
Out[41]:
True
In [42]:
False | False
Out[42]:
False

Tuples

In [43]:
t = (1,2,3)
t[0]
Out[43]:
1
In [44]:
#t[0] = 4 #ERROR: tuples can't be modified

Sets

In [45]:
{1,2,3}
Out[45]:
{1, 2, 3}
In [46]:
{1,2,3,1,2,1,2,3,3,3,3,2,2,2,1,1,2} #unique values
Out[46]:
{1, 2, 3}

Indexing and Selection

In [47]:
my_list[0] #one value using position (Iindex starts at 0)
Out[47]:
'a'
In [48]:
my_list[1:3] #many values using range (start is included, end is excluded.)
Out[48]:
['b', 'c']
In [49]:
my_list[:1] #if no value means from the beggining/ until the end
Out[49]:
['a']
In [50]:
my_list[0] = 'X' #modify value
my_list
Out[50]:
['X', 'b', 'c', 'd']
In [51]:
nest = [1,2,3,[4,5,[7,8]]] #nested list
nest[3][2][0] #selects the corresponded number of each nested item
Out[51]:
7
In [52]:
d['key1'] #selection in dictionaries using key
Out[52]:
'value1'

Comparison Operators

In [53]:
1 < 2 #smaller than
Out[53]:
True
In [54]:
1 > 2 #bigger than
Out[54]:
False
In [55]:
1 >= 1 #bigger or equal
Out[55]:
True
In [56]:
1 <= 4 #smaller or equal
Out[56]:
True
In [57]:
'hola' == 'hi' #equal
Out[57]:
False
In [58]:
'hola' != 'hi' #different
Out[58]:
True

Logical Operators

In [59]:
(1 > 2) and (2 < 3) #AND means ALL
(1 > 2) & (2 < 3) #equivalent
Out[59]:
False
In [60]:
(1 > 2) or (2 < 3) #OR means ANY
(1 > 2) | (2 < 3) #equivalent
Out[60]:
True
In [61]:
'x' in [1,2,3] #included
Out[61]:
False
In [62]:
'x' in ['x','y','z']
Out[62]:
True

if, elif, else

In [63]:
if 1 < 2:
    print('yes') #if true print
yes
In [64]:
if 1 < 2:
    print('first')
else:
    print('last') #if true print, else print
first
In [65]:
if 1 == 2:
    print('first')
elif 3 == 3:
    print('middle')
else:
    print('Last') #if true print, elif true print, else print
middle

Loops

In [66]:
seq = [1,2,3,4,5]
for item in seq:
    print(item)
1
2
3
4
5
In [67]:
for item in seq:
    print('number')
number
number
number
number
number
In [68]:
#while
i = 1
while i < 5:
    print('i is: {}'.format(i))
    i = i+1
i is: 1
i is: 2
i is: 3
i is: 4
In [69]:
#range
range(5)
for i in range(5):
    print(i)
0
1
2
3
4
In [70]:
#list comprehension
x = [1,2,3,4]
out = []

for item in x:
    out.append(item**2)
print(out)

[item**2 for item in x] #equivalent in one line
[1, 4, 9, 16]
Out[70]:
[1, 4, 9, 16]

Functions

In [71]:
def my_func(param1='default'):
    """
    Description.
    """
    print(param1)
    
my_func()
default
In [72]:
def square(x):
    return x**2

square(2)
Out[72]:
4

lambda expressions

In [73]:
def times2(var):
    return var*2
times2(2)

lambda var: var*2 #equivalent
Out[73]:
<function __main__.<lambda>(var)>
In [74]:
#map
seq = [1,2,3,4,5]

list(map(times2,seq))
list(map(lambda var: var*2,seq)) #equivalent
Out[74]:
[2, 4, 6, 8, 10]
In [75]:
#filter
list(filter(lambda item: item%2 == 0,seq))
Out[75]:
[2, 4]

Methods and functions

In [76]:
num = 4.24
round(num)
Out[76]:
4
In [77]:
st = 'Winter is coming!'
st.lower() #lower case
Out[77]:
'winter is coming!'
In [78]:
st.upper() #upper case
Out[78]:
'WINTER IS COMING!'
In [79]:
st.capitalize() #capitalize first word
Out[79]:
'Winter is coming!'
In [80]:
stsp = st.split() #split using spaces
stsp
Out[80]:
['Winter', 'is', 'coming!']
In [81]:
tweet = 'Winter is coming! #GOT'
tweet.split('#')[1] #split using special character and selecting after it
Out[81]:
'GOT'
In [82]:
d.keys() #for dictionaries, keys
Out[82]:
dict_keys(['key1', 'key2', 'key3'])
In [83]:
d.items() #for dictionaries, items
Out[83]:
dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
In [84]:
lst = [4,5,1,2,3]
lst
Out[84]:
[4, 5, 1, 2, 3]
In [85]:
min(lst)
Out[85]:
1
In [86]:
max(lst)
Out[86]:
5
In [87]:
sorted(lst)
Out[87]:
[1, 2, 3, 4, 5]
In [88]:
lst.pop() #drops last element
lst
Out[88]:
[4, 5, 1, 2]