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]:
a = 1.5 + 0.5j
print(a.real, a.imag)
print(type(a))
(1.5, 0.5)
<type 'complex'>
In [4]:
print(x+1)
6
In [5]:
print(a+1)
(2.5+0.5j)
In [6]:
print(x*2)
10
In [7]:
print(a*2)
(3+1j)
In [8]:
print(x/2)
2
In [9]:
print(x**2)
25
In [10]:
x+=1
print(x)
6
In [11]:
x *= 2
print(x)
12
In [12]:
print(x/5)
2
In [13]:
remainder  = 11 % 3
print(remainder)
2
In [14]:
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 [15]:
b = complex(2.5,1.5)
In [16]:
print(a, b, a+b, a-b, a/b)
((1.5+0.5j), (2.5+1.5j), (4+2j), (-1-1j), (0.5294117647058824-0.11764705882352938j))
In [17]:
print(a, a.conjugate(), abs(a), pow(a,2))
((1.5+0.5j), (1.5-0.5j), 1.5811388300841898, (2+1.5j))
In [18]:
userInput = raw_input('Enter an integer - ')
print(userInput)
Enter an integer - Bikash
Bikash
In [19]:
print(type(userInput))
<type 'str'>

Boolean¶

In [20]:
t = True
f = False
print(type(t),type(f))
(<type 'bool'>, <type 'bool'>)
In [21]:
print(t and f)
False
In [22]:
print(t and t)
True
In [23]:
print(t or f)
True
In [24]:
print(f or f)
False
In [25]:
print(not f)
True
In [26]:
print(t != f)
True
In [27]:
print(t != t)
False
In [28]:
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 [29]:
hello = 'hello'
world = 'world'
print(hello, world)
print(len(hello), len(world))
('hello', 'world')
(5, 5)
In [30]:
hw = hello + ' ' + world
print(hw)
hello world
In [31]:
hw12 = '%s %s %d' % (hello, world, 12)
print(hw12)
hello world 12
In [32]:
h = 'hello world!'
In [33]:
print(h.capitalize())
Hello world!
In [34]:
h = h.upper()
print(h)
HELLO WORLD!
In [35]:
h = h.lower()
print(h)
hello world!
In [36]:
str1 = h
print(str1)
hello world!
In [37]:
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 [38]:
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 [39]:
print(h.center(7))
hello world!
In [40]:
print(h.replace('l','imb'))
heimbimbo worimbd!
In [41]:
print('  world     is good'.strip()) # Strip leading and trailing whitespace
world     is good
In [42]:
print('  world     is good'.split())
['world', 'is', 'good']
In [43]:
print('  world     is good'.split("i"))
['  world     ', 's good']
In [44]:
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 [45]:
name  = 'Bikash'
age = 32
print(('%s is %d year\'s old') % (name, age))
Bikash is 32 year's old

Conditional Statement¶

In [46]:
if x is not 3:
    print('not 3')
not 3
In [47]:
if x is 4:
    print('Hmm')
Hmm
In [48]:
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 [49]:
if name in ['Bikash', 'Akash']:
    print('%s' % name)
Bikash
In [50]:
if name == 'Bikash' and age == 31:
    print('Good')
elif age == 33:
    print('Average')
else:
    print('Bad')
Bad
In [51]:
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 [52]:
primes = [2,3,5,7];
for prime in primes:
    print(prime)
2
3
5
7
In [53]:
for x in range(5):
    print(x)
0
1
2
3
4
In [54]:
for x in range(3,4):
    print(x)
3
In [55]:
for x in range(3,12,2):
    print(x)
3
5
7
9
11
In [56]:
for i in range(10,0,-1): #decreasing loop
    print(i)
10
9
8
7
6
5
4
3
2
1
In [57]:
count = 0
while count < 5:
    print(count)
    count += 1
0
1
2
3
4
In [58]:
# 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 [59]:
# 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 [60]:
# 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 [61]:
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 [62]:
list1 = [1,2,3,4]
print(list1)
[1, 2, 3, 4]
In [63]:
print(list1[0], list1[1], list1[2], list1[3])
(1, 2, 3, 4)
In [64]:
print(type(list1))
<type 'list'>
In [65]:
print(list1[-1])
4
In [66]:
print(list1[-4])
1
In [67]:
print(list1[-2])
3
In [68]:
list1[3] = 'bikash'
print(list1)
[1, 2, 3, 'bikash']
In [69]:
list1[4] = 'santra'
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-69-6bf620a8ab2d> in <module>()
----> 1 list1[4] = 'santra'

IndexError: list assignment index out of range
In [70]:
list1.append('santra')
print(list1)
[1, 2, 3, 'bikash', 'santra']
In [71]:
print(list1[2:4])
[3, 'bikash']
In [72]:
last = list1.pop()
print(last, list1)
('santra', [1, 2, 3, 'bikash'])
In [73]:
nums = list(range(0,10)) # last exclusive
print(nums)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [74]:
print(nums[2:6]) # last exclusive
[2, 3, 4, 5]
In [75]:
print(nums[3:])
[3, 4, 5, 6, 7, 8, 9]
In [76]:
print(nums[:3])
[0, 1, 2]
In [77]:
print(nums[:])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [78]:
print(nums[-1])
print(nums[:-1]) # last exclusive
9
[0, 1, 2, 3, 4, 5, 6, 7, 8]
In [79]:
print(nums[:-2])
[0, 1, 2, 3, 4, 5, 6, 7]
In [80]:
nums[2:4] = [11,12]
print(nums[2:8:2])
[11, 4, 6]
In [81]:
print(nums)
[0, 1, 11, 12, 4, 5, 6, 7, 8, 9]
In [82]:
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 [83]:
print(even*3)
[2, 4, 6, 8, 2, 4, 6, 8, 2, 4, 6, 8]
In [84]:
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 [85]:
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 [86]:
animals = ['cat', 'dog', 'monkey']
In [87]:
for animal in animals:
    print(animal)
cat
dog
monkey
In [88]:
for animal in enumerate(animals):
    print(animal)
(0, 'cat')
(1, 'dog')
(2, 'monkey')
In [89]:
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx+1, animal))
#1: cat
#2: dog
#3: monkey

List Comprehensions¶

In [90]:
nums = list(range(5))
print(nums)
[0, 1, 2, 3, 4]
In [91]:
squares = []
for x in nums:
    squares.append(x**2)
print(squares)
[0, 1, 4, 9, 16]
In [92]:
print(len(squares))
5
In [93]:
squares = [x**2 for x in nums] # Easy Approach
print(squares)
[0, 1, 4, 9, 16]
In [94]:
even_squares = [x**2 for x in nums if x % 2 == 0]
print(even_squares)
[0, 4, 16]
In [95]:
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 - Tanujit
Enter a string - ISI
Enter a string - Akash
Enter a string - ISI
Enter a string - Angshuman
Enter a string - ISI
Enter a string - Samriddha
Enter a string - ISI
[2, 3, 4, 5, 6, 7, 8, 9]
['Tanujit', 'ISI', 'Akash', 'ISI', 'Angshuman', 'ISI', 'Samriddha', 'ISI']
The second name on the names list is Bikash Santra

Dictionaries (Key, Value)¶

In [96]:
d = {'cat': 'cute', 'rat': 'bustard', 'frog': 'messy'}
In [97]:
print(d['cat'])
cute
In [98]:
print(d)
{'rat': 'bustard', 'frog': 'messy', 'cat': 'cute'}
In [99]:
for ind, key in enumerate(d):
    print('#%d: %s' % (ind,key))
#0: rat
#1: frog
#2: cat
In [100]:
for key in d:
    print(d[key])
bustard
messy
cute
In [101]:
print('cat' in d)
True
In [102]:
d['fish'] = 'wet'
In [103]:
print(d['fish'])
wet
In [104]:
print(d.get('monkey'))
None
In [105]:
print(d.get('monkey', 'N/A')) # Default if not found
N/A
In [106]:
print(d.get('fish'))
wet
In [107]:
print(d.get('fish', 'N/A')) # Default if not found
wet
In [108]:
d['rat'] = 'funny'
In [109]:
del d[('fish')]
In [110]:
print(d.get('fish','N/A'))
N/A
In [111]:
phonebook = {
   "John" : 938477566,
   "Jack" : 938377264,
   "Jill" : 947662781
}
print(phonebook)
{'Jill': 947662781, 'John': 938477566, 'Jack': 938377264}
In [112]:
del phonebook["John"]
print(phonebook)
{'Jill': 947662781, 'Jack': 938377264}
In [113]:
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 [114]:
print(type(phonebook))
<type 'dict'>

Loops in Dictionary¶

In [115]:
d = {'person': 2, 'cat': 4, 'spider': 8}
In [116]:
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 [117]:
nums = list(range(0, 10))
print(nums)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [118]:
even_num_to_square = {x: x**2 for x in nums if x % 2 == 0}
In [119]:
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 [120]:
animals = {'cats', 'dogs'}
In [121]:
print(animals)
set(['cats', 'dogs'])
In [122]:
animals = set(['cats', 'dogs']) # Alternate declairation
print(animals)
set(['cats', 'dogs'])
In [123]:
print('cats' in animals)
True
In [124]:
print('rats' in animals)
False
In [125]:
animals.add('rats')
In [126]:
print('rats' in animals)
True
In [127]:
print(len(animals))
3
In [128]:
animals.remove('rats')
In [129]:
print(len(animals))
2
In [130]:
animals = {'cat','dog','rat'}
In [131]:
for idx, animal in enumerate(animals):
    print('#%d: %s' % (idx+1, animal))
#1: rat
#2: dog
#3: cat
In [132]:
import math
nums = {int(math.sqrt(x)) for x in range(30)}
print(nums)
set([0, 1, 2, 3, 4, 5])

Tuples¶

In [133]:
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 [134]:
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 [135]:
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 [136]:
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 [137]:
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 [138]:
# Iterative version
def factorial(x):
    fact = 1
    for i in range(1,x+1):
        fact *= i
    return fact
print(factorial(3))
6
In [139]:
# Recursive Function

def fact(n):
    if n==0:
        return(1)
    else:
        return(n*fact(n-1))
print(fact(5))
120
In [140]:
# 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 [141]:
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 [142]:
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 [143]:
class school():
    def candidate(self):
        print('is paid rupees')
        
stu = school()
stu.candidate()
is paid rupees
In [144]:
# 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.
In [145]:
%whos
Variable                         Type                Data/Info
--------------------------------------------------------------
Greeter                          type                <class '__main__.Greeter'>
Vehicle                          classobj            __main__.Vehicle
a                                complex             (1.5+0.5j)
age                              int                 32
allNum                           list                n=8
animal                           str                 cat
animals                          set                 set(['rat', 'dog', 'cat'])
b                                complex             (2.5+1.5j)
build_sentence                   function            <function build_sentence at 0x7fb4a066f938>
car1                             __main__.Vehicle    <__main__.Vehicle instance at 0x7fb4a060f098>
car2                             __main__.Vehicle    <__main__.Vehicle instance at 0x7fb4a060f3f8>
count                            int                 5
d                                dict                n=10
data                             tuple               n=2
even                             list                n=4
even_num_to_square               dict                n=5
even_squares                     list                n=3
f                                bool                False
fact                             function            <function fact at 0x7fb4a066fb90>
factorial                        function            <function factorial at 0x7fb4a066f848>
g                                Greeter             <__main__.Greeter object at 0x7fb4a05ffa10>
h                                str                 hello world!
hello                            function            <function hello at 0x7fb4a066faa0>
hw                               str                 hello world
hw12                             str                 hello world 12
i                                int                 9
idx                              int                 2
ind                              int                 2
ind1                             int                 9
key                              str                 cat
last                             str                 santra
legs                             int                 4
list1                            list                n=4
list_benefits                    function            <function list_benefits at 0x7fb4a066fcf8>
math                             module              <module 'math' (built-in)>
mlist                            list                n=3
myfloat                          float               10.0
myint                            int                 20
mystring                         str                 Bikash
name                             str                 Jack
name_the_benefits_of_functions   function            <function name_the_benefi<...>ctions at 0x7fb4a066fb18>
names                            list                n=3
newS                             str                 world is good
number                           int                 938377264
numbers                          list                n=8
nums                             set                 set([0, 1, 2, 3, 4, 5])
odd                              list                n=4
phonebook                        dict                n=3
prime                            int                 7
primes                           list                n=4
proper_nouns                     list                n=2
remainder                        int                 2
sS                               str                   world is good   
school                           classobj            __main__.school
sign                             function            <function sign at 0x7fb4a066f758>
spS                              list                n=3
squares                          list                n=5
str1                             str                 hello world!
strings                          list                n=8
stu                              __main__.school     <__main__.school instance at 0x7fb4a060f440>
t                                tuple               n=2
userInput                        str                 Bikash
world                            str                 world
x                                int                 1
y                                int                 8

References¶

a) https://docs.python.org/2.7/tutorial/index.html
b) https://www.scipy-lectures.org/intro/language/python_language.html
c) https://github.com/kuleshov/cs228-material/blob/master/tutorials/python/cs228-python-tutorial.ipynb
d) https://www.learnpython.org/

Click here to download the source code of this tutorial.