iPython Notebook for this tutorial is available here.

Numbers

x = 10
y = 2
z = x + y
print x, y, z
print "%d + %d = %d" %(x,y,z)
10 2 12
10 + 2 = 12
a = 10.0
b = 3
c = a*b
print a, b, c
print "%f * %d = %f" %(a,b,c)
10.0 3 30.0
10.000000 * 3 = 30.000000
pi = 22/7
print "pi = %f -> This is not as expected because we used \
integer values 22 and 7. Use 22.0 and 7.0." %pi
pi = 22.0/7.0
print "pi = %f" %pi
print "pi = %.2f" %pi
pi = 3.000000 -> This is not as expected because we used integer values 22 and 7. Use 22.0 and 7.0.
pi = 3.142857
pi = 3.14
#typecasting
d = float(b) 
print b, d
3 3.0
e = a % b# modulo
print e
f = a ** b# power
print f
1.0
1000.0

Strings

str1 = "Learning"
print str1
len1 = len(str1)
print len1
Learning
8
str2 = 'Python!'
print str2
str3 = str1 + " " + str2
print str3
print "Concatanated string is: %s" %str3
len3 = len(str3)
print "Length of string %s is %d." %(str3, len3)
Python!
Learning Python!
Concatanated string is: Learning Python!
Length of string Learning Python! is 16.
# Slice a string
substr1 = str3[4:12] # [start:stop]
print substr1
substr2 = str3[4:12:1] # [start:stop:step]
print substr2
substr3 = str3[4:12:2] # [start:stop:step]
print substr3
ning Pyt
ning Pyt
nn y
# Reverse a string
revStr = str3[::-1]
print revStr
!nohtyP gninraeL
# indexing and  occurances
count = str3.count("n")
print count
index = str3.index("n") # index of first occurance
print index
indices = [i for i, x in enumerate(str3) if x == "n"]
print indices
3
4
[4, 6, 14]
# Split
all_str = str3.split(" ")
print all_str
['Learning', 'Python!']
# repeat a string
str4 = str1 * 10
print str4
LearningLearningLearningLearningLearningLearningLearningLearningLearningLearning
teststr1 = "Learn"
teststr2 = "C++"
ans1 = str3.startswith(teststr1)
ans2 = str3.endswith(teststr2)
print "Does %s starts with %s? %s" %(str3, teststr1, ans1)
print "Does %s ends with %s? %s" %(str3, teststr2, ans2)
Does Learning Python! starts with Learn? True
Does Learning Python! ends with C++? False

Lists

list1 = [10,20,30]
print list1
[10, 20, 30]
list2 = []
list2.append(100)
list2.append(200)
list2.append(300)
print "list2: %s" %list2
print "First number in list2 is %d." %list2[0]
print "Last number in list2 is %d." %list2[len(list2)-1]
list2: [100, 200, 300]
First number in list2 is 100.
Last number in list2 is 300.
for x in list2:
    print(x)
100
200
300
list3 = list1 * 3
print "Repeated list is: %s" %list3
Repeated list is: [10, 20, 30, 10, 20, 30, 10, 20, 30]
l = len(list3)
print "Length of list3 is %d." %l
Length of list3 is 9.
c = list3.count(10)
print "10 ocuurs %d times in list3." %c
10 ocuurs 3 times in list3.
# Multiply each element of a list my a number
list4 = [x*3 for x in list1]
print list4
[30, 60, 90]
list5 = list1 + list2
print "Concatanated list is: %s" %list5
Concatanated list is: [10, 20, 30, 100, 200, 300]
# element-wise addition without using numpy
list6 = [x+y for x,y in zip(list1,list2)]
print list6
[110, 220, 330]
# slicing a list
list7 = [x for x in range(10)]
print list7
list8 = list7[3:6] #[start:stop]
print list8
list9 = list7[0:9:2] #[start:stop:step]
print list9
list10 = list7[9:0:-2] #[start:stop:step]
print list10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5]
[0, 2, 4, 6, 8]
[9, 7, 5, 3, 1]
# delete an element in a list
print list7
del list7[5]
print list7
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 6, 7, 8, 9]

Control Flow

# while statement
# print fibonacci series
a, b = 0, 1
c = []
while b < 20:
    c.append(b)
    a, b = b, a+b
print c
[1, 1, 2, 3, 5, 8, 13]
# conditionals
x = int(raw_input("Enter an integer: "))
if (x%3==0):
    print "%d is divisible by 3"
else:
    print "%d is not divisible by 3" %x
Enter an integer: 10
10 is not divisible by 3
# for statement
result = []
for x in range(0,100,10):
    if (x%3==0):
        result.append(x)
print "Numbers divisible by 3 are: %s" %result
Numbers divisible by 3 are: [0, 30, 60, 90]

Dictionaries

phonebook = {'Sherlock': 976827, 'John': 973564}
phonebook['Mycroft'] = 972635
print phonebook
print phonebook['Sherlock']
{'John': 973564, 'Sherlock': 976827, 'Mycroft': 972635}
976827
print "Keys: %s" %phonebook.keys()
print "Values: %s" %phonebook.values()
Keys: ['John', 'Sherlock', 'Mycroft']
Values: [973564, 976827, 972635]
for k,v in phonebook.items():
    print "%s -> %d " %(k,v)
John -> 973564 
Sherlock -> 976827 
Mycroft -> 972635 

Sets

alphabets = set('abcdefghijk')
vowels = set('aeiou')
print alphabets
print vowels
print alphabets - vowels
print vowels - alphabets
print alphabets & vowels
print alphabets | vowels
set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j'])
set(['a', 'i', 'e', 'u', 'o'])
set(['c', 'b', 'd', 'g', 'f', 'h', 'k', 'j'])
set(['u', 'o'])
set(['a', 'i', 'e'])
set(['a', 'c', 'b', 'e', 'd', 'g', 'f', 'i', 'h', 'k', 'j', 'o', 'u'])
new_set = {x for x in vowels if x not in alphabets}
print new_set
set(['u', 'o'])
for idx, v in enumerate(vowels):
    print '#%d: %s' % (idx + 1, v)
#1: a
#2: i
#3: e
#4: u
#5: o

Tuples

t1 = 10, 20, 'a','abc'
print t1
(10, 20, 'a', 'abc')
v, x, y, z = t1
print v, x, y, z
10 20 a abc

List files in a directory

# list all files in a directory
filenames = !ls data
filenames
['butterfly.png',
 'conservatory.png',
 'flowers.png',
 'lenna.png',
 'painting.png']
# list files with a specific file extension
filenames = !ls data/*.png
filenames
['data/butterfly.png',
 'data/conservatory.png',
 'data/flowers.png',
 'data/lenna.png',
 'data/painting.png']

Random Numbers

import random
# generate a random number in a given range
rnd1 = random.randint(1, 100) #random integer between (start,stop)
print rnd1
rnd2 = random.randrange(1, 100, 3) # random integer between (start,stop) in steps of (step)
print rnd2
31
49
# select a random number from a given list
listA  = [x for x in range(0,100,10)]
rnd3 = random.choice(listA)
print listA
print rnd3
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
40
# sample a few numbers randomly from a given list
listB = random.sample(listA,  3)
print listB
[90, 40, 0]
# shuffle all the numbers in a given list
random.shuffle(listA)
print listA
[60, 80, 70, 30, 10, 0, 50, 40, 20, 90]
# generate same random numbers at each run
random.seed(2017)
rndA = random.randint(1, 100)
print rndA
20

Functions

def iseven(x):
    if (x%2 == 0):
        return 'true'
    else:
        return 'false'

for x in range(1,11):
    print x,iseven(x)
1 false
2 true
3 false
4 true
5 false
6 true
7 false
8 true
9 false
10 true
# optional argument
def join_strings(x,y, space=False):
    if (space):
        str = x + " " + y
    else:
        str = x + y
    return(str)

str1 = join_strings('Hello','World') 
print str1
str2 = join_strings('Hello','World', space=True)  
print str2
HelloWorld
Hello World