A Short Tutorial on Python Basics

Bikash Santra

Research Scholar, Indian Statistical Institute, Kolkata

Operators¶

In [1]:
x = 5
print(x)
print(type(x))
5
<type 'int'>
In [2]:
y = 2.6
print(type(y))
<type 'float'>
In [3]:
print(x+1)
6
In [4]:
print(x*2)
10
In [5]:
print(x/2)
2
In [6]:
print(x**2)
25
In [7]:
x+=1
print(x)
6
In [8]:
x *= 2
print(x)
12
In [9]:
print(x/5)
2
In [10]:
remainder  = 11 % 3
print(remainder)
2
In [11]:
print(y, y+1, y-2, y*2, y**2, y/5)
(2.6, 3.6, 0.6000000000000001, 5.2, 6.760000000000001, 0.52)
In [12]:
userInput = raw_input('Enter an integer - ')
print(userInput)
Enter an integer - 

Boolean¶

In [13]:
t = True
f = False
print(type(t),type(f))
(<type 'bool'>, <type 'bool'>)
In [14]:
print(t and f)
False
In [15]:
print(t and t)
True
In [16]:
print(t or f)
True
In [17]:
print(f or f)
False
In [18]:
print(not f)
True
In [19]:
print(t != f)
True
In [20]:
print(t != t)
False
In [21]:
x, y = 4, 8
print(x == 4 and y == 8)
print(x == 2)
print(x < 4)
print(y > 4)
print(x!=4)
True
False
False
True
False

Strings¶

In [22]:
hello = 'hello'
world = 'world'
print(hello, world)
print(len(hello), len(world))
('hello', 'world')
(5, 5)
In [23]:
hw = hello + ' ' + world
print(hw)
hello world
In [24]:
w12 = '%s %s %d' % (hello, world, 12)
print(hw12)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-24-8b97cdd83b5d> in <module>()
      1 w12 = '%s %s %d' % (hello, world, 12)
----> 2 print(hw12)

NameError: name 'hw12' is not defined
In [25]:
h = 'hello world!'
In [26]:
print(h.capitalize())
Hello world!
In [27]:
h = h.upper()
print(h)
HELLO WORLD!
In [28]:
h = h.lower()
print(h)
hello world!
In [29]:
str1 = h
print(str1)
hello world!
In [30]:
print(str1.count('h'))
print(str1[::-1])
print(str1.endswith('!'))
print(str1[1:len(str1)])
print(str1.index('l'))
1
!dlrow olleh
True
ello world!
2
In [31]:
print(h.rjust(7))
print(h.ljust(7))
print(h[:3])
print(h[:-1])
print(h[3:])
print(h[-1:])
hello world!
hello world!
hel
hello world
lo world!
!
In [32]:
print(h.center(7))
hello world!
In [33]:
print(h.replace('l','imb'))
heimbimbo worimbd!
In [34]:
print('  world     is good'.strip()) # Strip leading and trailing whitespace
world     is good
In [35]:
print('  world     is good'.split())
['world', 'is', 'good']
In [36]:
print('  world     is good'.split("i"))
['  world     ', 's good']
In [37]:
sS = '  world is good   '
print(len(sS))
newS = sS.strip()
print(newS, len(newS)) 
spS = newS.split()
print(spS, spS[0])
print(type(spS))
18
('world is good', 13)
(['world', 'is', 'good'], 'world')
<type 'list'>
In [38]:
name  = 'Bikash'
age = 32
print(('%s is %d year\'s old') % (name, age))
Bikash is 32 year's old

Conditional Statement¶

In [39]:
if x is not 3:
    print('not 3')
not 3
In [40]:
if x is 4:
    print('Hmm')
Hmm
In [41]:
name = 'Bikash'
age = 32
if name == 'Bikash' and age == 32:
    print('%s is %d year\'s old' % (name, age))
else:
    print('Shit!')
Bikash is 32 year's old
In [42]:
if name in ['Bikash', 'Akash']:
    print('%s' % name)
Bikash
In [43]:
if name == 'Bikash' and age == 31:
    print('Good')
elif age == 33:
    print('Average')
else:
    print('Bad')
Bad
In [44]:
mystring = 'Bikash'
myfloat = 10.00
myint = 20

# testing code
if mystring != "hello":
    print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
    print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
    print("Integer: %d" % myint)
String: Bikash
Float: 10.000000
Integer: 20

Loop¶

In [45]:
primes = [2,3,5,7];
for prime in primes:
    print(prime)
2
3
5
7
In [46]:
for x in range(5):
    print(x)
0
1
2
3
4
In [47]:
for x in range(3,4):
    print(x)
3
In [48]:
for x in range(3,12,2):
    print(x)
3
5
7
9
11
In [49]:
for i in range(10,0,-1): #decreasing loop
    print(i)
10
9
8
7
6
5
4
3
2
1
In [50]:
count = 0
while count < 5:
    print(count)
    count += 1
0
1
2
3
4
In [51]:
# Prints out 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break
    else:
        continue

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    
    print(x)
0
1
2
3
4
1
3
5
7
9
In [52]:
# Prints out 0,1,2,3,4 and then it prints "count value reached 5"

count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))

# Prints out 1,2,3,4
for i in range(1, 10):
    print(i)
else:
    print("this is not printed because for loop is terminated because of break but not due to fail in condition")
0
1
2
3
4
count value reached 5
1
2
3
4
5
6
7
8
9
this is not printed because for loop is terminated because of break but not due to fail in condition
In [53]:
# Prints out 0,1,2,3,4

count = 0
while True:
    print(count)
    count += 1
    if count >= 5:
        break

# Prints out only odd numbers - 1,3,5,7,9
for x in range(10):
    # Check if x is even
    if x % 2 == 0:
        continue
    print(x)
0
1
2
3
4
1
3
5
7
9
In [54]:
numbers = [
    951, 402, 984, 651, 360, 69, 408, 319, 601, 485, 980, 507, 725, 547, 544,
    615, 83, 165, 141, 501, 263, 617, 865, 575, 219, 390, 984, 592, 236, 105, 942, 941,
    386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
    399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
    815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
    958, 609, 842, 451, 688, 753, 854, 685, 93, 857, 440, 380, 126, 721, 328, 753, 470,
    743, 527
]
print(len(numbers))
for x in numbers:
    print(x)
    if x%2 == 0:
        print(x)
    elif x == 237:
        break
    else:
        continue
else:
    print("It is done")
100
951
402
402
984
984
651
360
360
69
408
408
319
601
485
980
980
507
725
547
544
544
615
83
165
141
501
263
617
865
575
219
390
390
984
984
592
592
236
236
105
942
942
941
386
386
462
462
47
418
418
907
344
344
236
236
375
823
566
566
597
978
978
328
328
615
953
345
399
162
162
758
758
219
918
918
237

Containers¶

List [ ]¶

In [55]:
list1 = [1,2,3,4]
print(list1)
[1, 2, 3, 4]
In [56]:
print(list1[0], list1[1], list1[2], list1[3])
(1, 2, 3, 4)
In [57]:
print(type(list1))
<type 'list'>
In [58]:
print(list1[-1])
4
In [59]:
print(list1[-4])
1
In [60]:
print(list1[-2])
3
In [61]:
list1[3] = 'bikash'
print(list1)
[1, 2, 3, 'bikash']
In [62]:
list1[4] = 'santra'
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-62-6bf620a8ab2d> in <module>()
----> 1 list1[4] = 'santra'

IndexError: list assignment index out of range
In [63]:
list1.append('santra')
print(list1)
[1, 2, 3, 'bikash', 'santra']
In [64]:
print(list1[2:4])
[3, 'bikash']
In [65]:
last = list1.pop()
print(last, list1)
('santra', [1, 2, 3, 'bikash'])
In [66]:
nums = list(range(0,10)) # last exclusive
print(nums)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [67]:
print(nums[2:6]) # last exclusive
[2, 3, 4, 5]
In [68]:
print(nums[3:])
[3, 4, 5, 6, 7, 8, 9]
In [69]:
print(nums[:3])
[0, 1, 2]
In [70]:
print(nums[:])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [71]:
print(nums[-1])
print(nums[:-1]) # last exclusive
9
[0, 1, 2, 3, 4, 5, 6, 7, 8]
In [72]:
print(nums[:-2])
[0, 1, 2, 3, 4, 5, 6, 7]
In [73]:
nums[2:4] = [11,12]
print(nums[2:8:2])
[11, 4, 6]
In [74]:
print(nums)
[0, 1, 11, 12, 4, 5, 6, 7, 8, 9]
In [75]:
even = [2, 4, 6, 8]
odd = [1, 3, 5, 7]
allNum = even + odd
print(allNum, type(allNum))
([2, 4, 6, 8, 1, 3, 5, 7], <type 'list'>)
In [76]:
print(even*3)
[2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8]
In [77]:
mlist = [1, 2, 3]
print('A list is %s %s' % (mlist,mlist))
A list is [1, 2, 3] [1, 2, 3]

Loops in List¶

In [78]:
for i in range(100):
    print(2**i)
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
2147483648
4294967296
8589934592
17179869184
34359738368
68719476736
137438953472
274877906944
549755813888
1099511627776
2199023255552
4398046511104
8796093022208
17592186044416
35184372088832
70368744177664
140737488355328
281474976710656
562949953421312
1125899906842624
2251799813685248
4503599627370496
9007199254740992
18014398509481984
36028797018963968
72057594037927936
144115188075855872
288230376151711744
576460752303423488
1152921504606846976
2305843009213693952
4611686018427387904
9223372036854775808
18446744073709551616
36893488147419103232
73786976294838206464
147573952589676412928
295147905179352825856
590295810358705651712
1180591620717411303424
2361183241434822606848
4722366482869645213696
9444732965739290427392
18889465931478580854784
37778931862957161709568
75557863725914323419136
151115727451828646838272
302231454903657293676544
604462909807314587353088
1208925819614629174706176
2417851639229258349412352
4835703278458516698824704
9671406556917033397649408
19342813113834066795298816
38685626227668133590597632
77371252455336267181195264
154742504910672534362390528
309485009821345068724781056
618970019642690137449562112
1237940039285380274899124224
2475880078570760549798248448
4951760157141521099596496896
9903520314283042199192993792
19807040628566084398385987584
39614081257132168796771975168
79228162514264337593543950336
158456325028528675187087900672
316912650057057350374175801344
633825300114114700748351602688
In [79]:
animals = ['cat', 'dog', 'monkey']
In [80]:
for animal in animals:
    print(animal)
cat
dog
monkey
In [81]:
for animal in enumerate(animals):
    print(animal)
(0, 'cat')
(1, 'dog')
(2, 'monkey')
In [82]:
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx+1, animal))
#1: cat
#2: dog
#3: monkey

List Comprehensions¶

In [83]:
nums = list(range(5))
print(nums)
[0, 1, 2, 3, 4]
In [84]:
squares = []
for x in nums:
    squares.append(x**2)
print(squares)
[0, 1, 4, 9, 16]
In [85]:
print(len(squares))
5
In [86]:
squares = [x**2 for x in nums] # Easy Approach
print(squares)
[0, 1, 4, 9, 16]
In [87]:
even_squares = [x**2 for x in nums if x % 2 == 0]
print(even_squares)
[0, 4, 16]
In [88]:
numbers = []
strings = []
names = ["John", "Eric", "Jessica"]
proper_nouns = ['Bikash', 'Santra']

# write your code here
for i in range(2,10):
    numbers.append(i)
    strings.append(raw_input('Enter a string - '))

# this code should write out the filled arrays and the second name in the names list (Eric).
print(numbers)
print(strings)
print("The second name on the names list is %s %s" % (proper_nouns[0], proper_nouns[1]))
Enter a string - 
Enter a string - 
Enter a string - 
Enter a string - 
Enter a string - 
Enter a string - 
Enter a string - 
Enter a string - 
[2, 3, 4, 5, 6, 7, 8, 9]
['', '', '', '', '', '', '', '']
The second name on the names list is Bikash Santra

Dictionaries (Key, Value)¶

In [89]:
d = {'cat': 'cute', 'rat': 'bustard', 'frog': 'messy'}
In [90]:
print(d['cat'])
cute
In [91]:
print(d)
{'rat': 'bustard', 'frog': 'messy', 'cat': 'cute'}
In [92]:
for ind, key in enumerate(d):
    print('#%d: %s' % (ind,key))
#0: rat
#1: frog
#2: cat
In [93]:
for key in d:
    print(d[key])
bustard
messy
cute
In [94]:
print('cat' in d)
True
In [95]:
d['fish'] = 'wet'
In [96]:
print(d['fish'])
wet
In [97]:
print(d.get('monkey'))
None
In [98]:
print(d.get('monkey', 'N/A')) # Default if not found
N/A
In [99]:
print(d.get('fish'))
wet
In [100]:
print(d.get('fish', 'N/A')) # Default if not found
wet
In [101]:
d['rat'] = 'funny'
In [102]:
del d[('fish')]
In [103]:
print(d.get('fish','N/A'))
N/A
In [104]:
phonebook = {
   "John" : 938477566,
   "Jack" : 938377264,
   "Jill" : 947662781
}
print(phonebook)
{'Jill': 947662781, 'John': 938477566, 'Jack': 938377264}
In [105]:
del phonebook["John"]
print(phonebook)
{'Jill': 947662781, 'Jack': 938377264}
In [106]:
phonebook = {"John" : 938477566,"Jack" : 938377264,"Jill" : 947662781}
for name, number in phonebook.items():
    print("Phone number of %s is %d" % (name, number))
Phone number of Jill is 947662781
Phone number of John is 938477566
Phone number of Jack is 938377264
In [107]:
print(type(phonebook))
<type 'dict'>

Loops in Dictionary¶

In [108]:
d = {'person': 2, 'cat': 4, 'spider': 8}
In [109]:
for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal, legs))
A person has 2 legs
A spider has 8 legs
A cat has 4 legs

Dictionary comprehensions¶

In [110]:
nums = list(range(0, 10))
print(nums)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [111]:
even_num_to_square = {x: x**2 for x in nums if x % 2 == 0}
In [112]:
print(even_num_to_square) # Search how it works, sequence is not maintained
{0: 0, 8: 64, 2: 4, 4: 16, 6: 36}

Sets¶

In [113]:
animals = {'cats', 'dogs'}
In [114]:
print(animals)
set(['cats', 'dogs'])
In [115]:
animals = set(['cats', 'dogs']) # Alternate declairation
print(animals)
set(['cats', 'dogs'])
In [116]:
print('cats' in animals)
True
In [117]:
print('rats' in animals)
False
In [118]:
animals.add('rats')
In [119]:
print('rats' in animals)
True
In [120]:
print(len(animals))
3
In [121]:
animals.remove('rats')
In [122]:
print(len(animals))
2
In [123]:
animals = {'cat','dog','rat'}
In [124]:
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx+1, animal))
#1: rat
#2: dog
#3: cat
In [125]:
import math
nums = {int(math.sqrt(x)) for x in range(30)}
print(nums)
set([0, 1, 2, 3, 4, 5])

Tuples¶

In [2]:
d = {(x, x+1): x for x in range(10)}
t = (2,3)
print (type(d))
print(type(t))
print(d)
print(list(t))
<type 'dict'>
<type 'tuple'>
{(0, 1): 0, (1, 2): 1, (6, 7): 6, (5, 6): 5, (7, 8): 7, (8, 9): 8, (4, 5): 4, (2, 3): 2, (9, 10): 9, (3, 4): 3}
[2, 3]
In [127]:
d[t] = 1000 
print(d)
{(0, 1): 0, (1, 2): 1, (6, 7): 6, (5, 6): 5, (7, 8): 7, (8, 9): 8, (4, 5): 4, (2, 3): 1000, (9, 10): 9, (3, 4): 3}
In [128]:
for ind1,data in enumerate(d):
    print('#%d: %s' % (ind1,data))
#0: (0, 1)
#1: (1, 2)
#2: (6, 7)
#3: (5, 6)
#4: (7, 8)
#5: (8, 9)
#6: (4, 5)
#7: (2, 3)
#8: (9, 10)
#9: (3, 4)

Functions¶

In [129]:
def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

for x in [-1, 0, 1]:
    print(sign(x))
negative
zero
positive
In [130]:
def hello(name, loud=False):
    if loud:
        print('HELLO, %s!' % name.upper())
    else:
        print('Hello, %s' % name)

hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True)  # Prints "HELLO, FRED!"
Hello, Bob
HELLO, FRED!
In [131]:
# Iterative version

def factorial(x):
    fact = 1
    for i in range(1,x+1):
        fact *= i
    return fact
print(factorial(3))
6
In [132]:
# Recursive Function

def fact(n):
    if n==0:
        return(1)
    else:
        return(n*fact(n-1))
print(fact(5))
120
In [133]:
# Modify this function to return a list of strings as defined above
def list_benefits():
    return ['More','More-More', 'Greater']

# Modify this function to concatenate to each benefit - " is a benefit of functions!"
def build_sentence(benefit):
    return benefit + ' effort is required.'

def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefit in list_of_benefits:
        print(build_sentence(benefit))

name_the_benefits_of_functions()
More effort is required.
More-More effort is required.
Greater effort is required.

Classes¶

In [134]:
class Greeter(object):

    # Constructor
    def __init__(self, name):
        self.name = name  # Create an instance variable

    # Instance method
    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

g = Greeter('Fred')  # Construct an instance of the Greeter class
g.greet()            # Call an instance method; prints "Hello, Fred"
g.greet(loud=True)   # Call an instance method; prints "HELLO, FRED!"
Hello, Fred
HELLO, FRED!
In [135]:
class school(object):
    def __init__(self,name):
        self.name = name
        
    def candidate(self, x):
        if x==5000:
            print('%s is paid %d rupees' % (self.name,x))
        else:
            print('%s is paid %d rupees' % (self.name,x))
stu = school('Bikash')
stu.candidate(5000)
Bikash is paid 5000 rupees
In [136]:
class school():
    def candidate(self):
        print('is paid rupees')
        
stu = school()
stu.candidate()
is paid rupees
In [137]:
# define the Vehicle class
class Vehicle:
    name = ""
    kind = "car"
    color = ""
    value = 100.00
    def description(self):
        desc_str = "%s is a %s %s worth $%.2f." % (self.name, self.color, self.kind, self.value)
        return desc_str
# your code goes here
car1 = Vehicle()
car2 = Vehicle()
car1.name = 'Benz'
car1.color = 'Red'
car2.name = 'BMW'
car2.color = 'Silver'

# test code
print(car1.description())
print(car2.description())
Benz is a Red car worth $100.00.
BMW is a Silver car worth $100.00.

References¶

a) https://github.com/kuleshov/cs228-material/blob/master/tutorials/python/cs228-python-tutorial.ipynb
b) https://www.learnpython.org/

Click here to download the source code of this tutorial.