Python
Printing
print('My number is: {one}, and my name is: {two}'.format(one=num,two=name)) or
print('My number is: {}, and my name is: {}'.format(num,name))
Lists
my_list = ['a','b','c']
my_list.append('d')
my_list[1:] - prints all values from index one (slicing)
nest = [1,2,3,[4,5,['target']]] - nested
Dictionaries
d = {'key1':'item1','key2':'item2'}
d['key1']
d = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]} - To get word hello
d['k1'][3]['tricky'][3]['target'][3] - output 'hello'
Tuples
Tuples are similar to array, but tuple values cannot be changes i.e Tuples are immutable
t = (1,2,3)
t[0] = 5 - Is not allowed
Sets
{1,2,3}
Comparison Operator
Returns boolean
1> 2
'h1' == 'bye'
Logical Operator
(1 > 2) and (2 < 3)
(1 == 2) or (2 == 3) or (4 == 4)
returns boolean
if elif else
if 1 == 2:
print('first')
elif 3 == 3:
print('middle')
else:
print('Last')
for loops
seq = [1,2,3,4,5]
for item in seq:
print(item)
while loops
i = 1
while i < 5:
print('i is: {}'.format(i))
i = i+1
range
range(5) - returns range of (0,5)
for i in range(5):
print(i)
list(range(5)) - convert range to list
list comprehension
x = [1,2,3,4]
out = []
for item in x:
out.append(item**2)
print(out) - result would be [1, 4, 9, 16]
or
[item**2 for item in x] - will return the same result
functions
def my_func(param1='default'):
"""
Docstring goes here. - When """ are put in function it will be a docs for the function
"""
print(param1)
def square(x):
return x**2
def domainGet(email): - returns the domain name of email address
return email.split('@')[-1]
def countDog(st): - Count number of 'dog' in the string passed
count = 0
for word in st.lower().split():
if word == 'dog':
count += 1
return count
Lambda expressions
def times2(var):
return var*2 - This function can be written in lambda using
lambda var: var*2
list(filter(lambda word: word[0]=='s',seq)) - To filter out the words starting with s
map and filter
seq = [1,2,3,4,5]
map(times2,seq) - Where times2 is a function. Here function will be called for each sequence and the result would be in map.
list(map(times2,seq)) - Type cast to list and the values would be [2, 4, 6, 8, 10]
list(map(lambda var: var*2,seq)) - Same as above using lambda
Items can be filtered using filter function
list(filter(lambda item: item%2 == 0,seq))
def times2(var,seq):
return var*seq+1
seq = [1,2,3,4,5]
list(map(times2,seq,seq))
methods
st = 'hello my name is Babu'
st.lower() st.upper() st.split()
dic.keys() dic.items()
'x' in [1,2,3] - False 'x' in ['x','y','z'] - True
Links
Sample Data - https://www.kaggle.com/