Python Learning Notes

Programming | 26 March 2017

In this page, you will find the syntax, modules and most common how to’s of Python programming language. This might be helpful for you to find python syntax and code quickly in a single web page. Click on any of the contents in the sidebar to view the python code.

Note: If you are new to programming, learning Python is the best way to start. Because, Python is easier to learn than any other programming language out there as it is concise, expressive, productive, has larger community, has rich set of libraries, frameworks and requires less time to write code.

Update: As Python2 faces end of life, the below code only supports Python3.

Basics

Hello Worldcode

1
2
3
4
5
6
7
print("Hello World")
# prints "Hello World"
# above line is a comment
'''
This is a multi-line
comment in python
'''

Data typescode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# declare an integer
a = 12
print(a)       # prints "12"
print(type(a)) # prints <type 'int'>

# declare a float
b = 1.7
print(b)       # prints "1.7"
print(type(b)) # prints <type 'float'>

# declare a string
c = "Python"
print(c)       # prints "Python"
print(type(c)) # prints <type 'str'>

# declare a boolean
d = True
print(d)       # prints "True"
print(type(d)) # prints <type 'bool'>

Multiple variable assignmentscode

1
2
3
4
5
6
7
8
9
# assign values to multiple variables in a single line
a, b, c = 1, 2, 3

# assign values with different data types to multiple variables in a single line
a, b, c = 1, 3.5, "hello"

print(type(a)) # prints <type 'int'>
print(type(b)) # prints <type 'float'>
print(type(c)) # prints <type 'str'>

Math operationscode

1
2
3
4
5
6
7
a = 10

print(a + 1)  # Addition: prints "11"
print(a - 1)  # Subtraction: prints "9"
print(a * 2)  # Multiplication: prints "20"
print(a / 2)  # Division: prints "5"
print(a ** 2) # Exponentiation: prints "100"

Logical operationscode

1
2
3
4
5
6
7
8
# declare some boolean variables
x = True
y = False

print(x and y)  # prints "False"
print(x or y)   # prints "True"
print(not x)    # prints "False"
print(x & y)    # prints "False"

Conditionscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# if-elif-else statements

import random
a = [50, 100, 200, 300]

# pick a random number from the list "a"
b = random.choice(a)

# the conditionals
if (b < 100):
    print("Number - " + str(b) + " is less than 100")
elif (b >= 100 and b < 200):
    print("Number - " + str(b) + " is greater than or equal to 100 but less than 200")
else:
    print("Number -" + str(b) + " is greater than or equal to 200")

# for me it prints
# Number - 100 is greater than or equal to 100 but less than 200

Loopscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# while loop
c = 0
while (c < 10):
    print(c,  end='')
    c += 1

# prints 0123456789

# for loop
numbers = [1, 2, 4]
for x in numbers:
    print(x)

# prints 1
#        2
#        4

x = 5
for c in range(x):
    print(c)

# prints 0
#        1
#        2
#        3
#        4

Stringscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# declare two strings
a = "Python"
b = " is awesome!"

print(len(a))                        # Length of the string: prints "6"
print(len(b))                        # prints "12"
print(a + b)                         # String concatenation: prints "Python is awesome!"
print(a, b)                          # prints "Python  is awesome!"
print("{}{}".format(a, b))          # prints "Python is awesome!"
print("%s%s" % (a, b))               # sprintf style formatting: prints "Python is awesome!"
print(a.upper())                    # converts all characters to uppercase: prints "PYTHON"
print(a.lower())                     # converts all characters to lowercase: prints "python"
print(b.strip())                     # removes trailing and leading whitespaces: prints "is awesome!"
print(b.replace("awesome", "great")) # replace a substring with a new string: prints " is great!"

Listscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# declare a list
l = [1,2,3,4,5]

# length of list
print(len(l))      # prints "5"

# indexing
print(l[0])        # prints "1"
print(l[1])        # prints "2"
print(l[len(l)-1]) # prints "5"
print(l[-1])       # negative indexing: prints "5"

# insert and remove
l.append(6)        # inserts "6" at last
print(l)            # prints "[1,2,3,4,5,6]"
item = l.pop()     # removes last element and returns that element
print(item)         # prints "6"
l.append("string") # adds different data type too
print(l)            # prints "[1,2,3,4,5,'string']"
l.pop()            # removes last string element

# slicing list
print(l[1:2])       # prints "2"
print(l[1:3])       # prints "2,3"
print(l[0:])        # prints "[1,2,3,4,5,'string']"
print(l[0:-1])      # prints "[1,2,3,4,5]"
print(l[:])         # prints "[1,2,3,4,5,'string']"

# loop over the list
for item in l:
    print(item)     # prints each item in list one by one

# enumerate over the list
for i, item in enumerate(l):
    print("{}-{}".format(i, item)) # prints each item with its index


# squaring elements in a list
for item in l:
    if item%2 == 0:
        print(item2)      # square each even number in the list

# above can be achieved using a list comprehension too! (one-line)
print([x2 for x in l if x%2==0])

# sort the list
b = [5, 7, 2, 4, 9]

# ascending order
b.sort()
print(b)  # prints [2, 4, 5, 7, 9]

# descending order
b.sort(reverse=True)
print(b) # prints [9, 7, 5, 4, 2]

# reverse the list (notice this is not descending order sort)
a = ["dhoni", "sachin", "warner", "abd"]
a.reverse()
print(a) # prints ['abd', 'warner', 'sachin', 'dhoni']

# count of object in list
a = [66, 55, 44, 22, 11, 55, 22] 
print(a.count(22)) # prints 2

Tuplescode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# declare a tuple
t = (500, 200)

print(type(t))    # prints "<type 'tuple'>"
print(t[1])       # prints 200

# tuple of tuples
tt = ((200,100), t)

print(tt)         # prints "((200, 100), (500, 200))"
print(tt[1])      # prints "(500, 200)"

# loop over tuple
for item in t:
    print(item)   # prints each item in the tuple


# built-in tuple commands
print(len(t)) # prints the length of tuple which is 2
print(max(t)) # prints the max-valued element which is 500
print(min(t)) # prints the min-valued element which is 200

# convert list to tuple
l = [400, 800, 1200]
l_to_t = tuple(l)

print(type(l_to_t)) # prints <class 'tuple'>

Setcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# set is a collection of unordered and unindexed data which is written with curly brackets.
s = {"ironman", "hulk", "thor", "thanos"}

for x in s:
    print(x)

'''
prints 
ironman
thor
hulk
thanos
'''

# check if value exist in set
if "thanos" in s:
    print("endgame") # prints 'endgame'

# add a single item to a set using 'add'
s.add("rocket")

# add multiple items to a set using 'update'
s.update(["blackhood", "blackwidow"])

# get length of a set
print(len(s)) # prints 7

# 'remove' or 'discard' an item from the set
# 'remove' raise an error if item to remove does not exist
# 'discard' will not raise any error if item to remove does not exist
s.remove("thanos")
s.discard("blackwidow")

# clear the set
s.clear()

# delete the set
del s

Dictionariescode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# declare a dictionary
d = { "1" : "Ironman", 
      "2" : "Captain America", 
      "3" : "Thor"
    }

print(type(d))    # prints "<type 'dict'>"
print(d["1"])     # prints "Ironman"

# loop over dictionary
for key in d:
    print(key)    # prints each key in d
    print(d[key]) # prints value of each key in d (unsorted)

# change values in the dictionary
d["2"] = "Hulk"
for key, value in d.items():
    print(key + " - " + value)

'''
prints
1 - Ironman
2 - Hulk
3 - Thor
'''

# check if key exists in a dictionary
if "3" in d:
    print("Yes! 3 is " + d["3"])
# prints 'Yes! 3 is Thor'

# get length of the dictionary
print(len(d)) # prints 3

# insert a key-value pair to a dictionary
d["4"] = "Thanos"

# remove a key-value pair from the dictionary
d.pop("4")

# same thing using 'del' keyword
del d["2"]

# clear a dictionary
d.clear()

Exception Handlingcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# try-except-finally
# try: test a block of code for errors.
# except: allows handling of errors.
# finally: execute code, regardless of the result of try and except blocks.
try:
    print(x)
except:
    print("Something is wrong!")

# prints 'Something is wrong!' as x is not defined

try:
    print(x)
except: 
    print("Something is wrong!")
finally:
    print("Finally always execute after try-except.")

# prints
# Something is wrong!
# Finally always execute after try-except.

Functionscode

1
2
3
4
def squared(x):
    return x*x

print(squared(2))   # prints "4"

Intermediate

List Comprehensionscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
nums = [1, 2, 3, 4, 5, 6, 7]

# traditional for loop
l = []
for n in nums:
    l.append(n)
print(l) # prints '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

# meet list comprehension
l = [n for n in nums]
print(l) # prints '[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]'

# get square of each number
l = [n*n for n in nums]
print(l) # prints '[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]'

# same thing achieved using 'map' + 'lambda'
# 'map' means running everything in the list for a certain function
# 'lambda' means an anonymous function
l = map(lambda n: n*n, nums)
for x in l:
    print(x) 

# prints 
# 1
# 4
# 9
# 16
# 25
# 36
# 49
# 64
# 81
# 100

# using 'if' in list comprehension
l = [n for n in nums if n%2 == 0]
print(l) # prints '[2, 4, 6, 8, 10]'

# returning tuples with two for loops in list comprehension
l = []
for letter in "ab":
    for num in range(2):
        l.append((letter, num))
print(l) # prints '[('a', 0), ('a', 1), ('b', 0), ('b', 1)]'

# same thing using list comp
l = [(letter, num) for letter in "ab" for num in range(2)]
print(l) # prints '[('a', 0), ('a', 1), ('b', 0), ('b', 1)]'

Dict Comprehensionscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
names = ["Robert Downey Jr", "Chris Evans", "Chris Hemsworth", "Mark Ruffalo"]
heros = ["Ironman", "Captain America", "Thor", "Hulk"]

# traditional dictionary using zip()
d = {}
for name, hero in zip(names, heros):
    d[name] = hero
for name in d:
    print(name + " - " + d[name])

'''
prints 
Mark Ruffalo - Hulk
Chris Hemsworth - Thor
Robert Downey Jr - Ironman
Chris Evans - Captain America
'''

# meet dict comprehension
d = {name: hero for name, hero in zip(names, heros)}
for name in d:
    print(name + " - " + d[name])

'''
prints 
Mark Ruffalo - Hulk
Chris Hemsworth - Thor
Robert Downey Jr - Ironman
Chris Evans - Captain America
'''

# dict comprehension with condition
d = {name: hero for name, hero in zip(names, heros) if name != "Mark Ruffalo"}
for name in d:
    print(name + " - " + d[name])

'''
prints 
Chris Hemsworth - Thor
Robert Downey Jr - Ironman
Chris Evans - Captain America
'''

Set Comprehensionscode

1
2
3
4
5
6
7
8
9
10
11
nums = [1, 1, 2, 1, 3, 4, 4, 5, 5, 6, 7, 8, 8, 9]

# traditional set (list of unique elements)
s = set()
for n in nums:
    s.add(n)
print(s) # prints {1, 2, 3, 4, 5, 6, 7, 8, 9}

# meet set comprehension
s = {n for n in nums}
print(s) # prints {1, 2, 3, 4, 5, 6, 7, 8, 9}

Generator Expressionscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# I need to yield 'n*n' for each 'n' in nums
nums = [1,2,3,4,5,6,7,8,9]

# traditional generator function
def gen_func(nums):
    for n in nums:
        yield n*n

m = gen_func(nums)
for i in m:
    print(i)

# generator expression
m = (n*n for n in nums)
for i in m:
    print(i)

'''
both prints 
1 
4 
9 
16
25
36
49
64
81
'''

Lambdacode

1
2
3
4
5
6
7
8
9
10
11
# a lambda function = a small anonymous function
# takes any number of arguments, but can have only one expression
# lambda arguments : expression

# lambda function with one argument
add_hundred = lambda x : x + 100
print(add_hundred(5)) # prints 105

# lambda function with multiple arguments
multiply = lambda a, b, c : a*b*c
print(multiply(10,5,10)) # prints 500

Generatorscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# generators uses the keyword 'yield' to take one element at a time
# it helps increase performance and make code more readable
def square_numbers(nums):
    for i in nums:
        yield (i*i)

nums = square_numbers([1,2,3,4,5])
print(type(nums)) # <class 'generator'>
print(nums)       # <generator object square_numbers at 0x0000018525078B48>
for n in nums:
    print(n)
# prints 
# 1
# 4
# 9
# 16
# 25


# another example
def people_list(num_people):
    result = []
    for i in xrange(num_people):
        person = {
                   "id"    : i,
                   "name"  : random.choice(names),
                   "major" : random.choice(majors) 
                }
        result.append(person)
    return result

def people_generator(num_people):
    for i in xrange(num_people):
        person = {
                    "id"    : i,
                    "name"  : random.choice(names),
                    "major" : random.choice(majors)
                  }
        yield person

t1 = time.clock()
people = people_list(1000000)
t2 = time.clock()

print("[INFO] Took {} seconds".format(t2-t1))
# prints
# [INFO] Took 1.2467856325541558 seconds

t1 = time.clock()
people = people_generator(1000000)
t2 = time.clock()

print("[INFO] Took {} seconds".format(t2-t1))
# prints
# [INFO] Took 0.12330942238179077 seconds

args & kwargscode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# *args used to pass non-keyworded variable-length arguments to a function
def my_nums(*args):
    for n in args:
        print(n, end=" ")
    print(type(args))

# prints
my_nums(1,2,4,5,6)
# prints 
# '1 2 4 5 6'
# <class 'tuple'>

# **kwargs used to pass keyworded variable-length arguments to a function
def my_fullname(**kwargs):
    for key, value in kwargs.items():
        print(key + " - " + value)
    print(type(kwargs))

# prints
my_fullname(firstname="Gogul", lastname="Ilango") 
# prints 
# lastname - Ilango
# firstname - Gogul
# <class 'dict'>

Modules

re rules

Identifiers

\d any number
\D anything but a number
\s space
\S anything but a space
\w any character
\W anything but a character
. any character, except for a newline
\b the whitespace around words
\. a period

Modifiers

{1,3} expecting 1-3 digits ~ \d{1,3}
+ match 1 or more
? match 0 or 1
* match 0 or more
$ match the end of a string
^ match the start of a string
| either or (\d{1-3} | \w{5-6})
[] range or variance
{x} expecting "x" amount (of digits)

White Space Characters

\n new line
\s space
\t tab
\e escape
\f form feed
\r return
Regular Expressions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import re 

# multi-line string example
str = '''
Rahul is 19 years old, and Ashok is 24 years old.
Murali is 65, and his grandfather, Karthik, is 77.
'''

# findall()
ages  = re.findall(r'\d{1,3}', str)
names = re.findall(r'[A-Z][a-z]*', str) 
print(ages)  # prints ['19', '24', '65', '77']
print(names) # prints ['Rahul', 'Ashok', 'Murali', 'Karthik']

# finditer()
ages = re.finditer(r'\d{1,3}', str)
for m in ages:
    print(m.group())

# prints 
# 19
# 24
# 65
# 77

# split()
str = "This is an example string"
splitted = re.split(r'\s*', str)
print(splitted) # prints ['This', 'is', 'an', 'example', 'string']

# match()
str = "Dogs are braver than Cats"
matches = re.match(r'[A-Z][a-z]*', str)
print(matches.group()) # prints "Dogs"

# search()
str = "For data science help, reach support@datacamp.com"
searches = re.search(r'([\w]+)@([\w\.]+)', str)
print(searches.group())  # prints support@datacamp.com
print(searches.group(1)) # prints support
print(searches.group(2)) # prints datacamp.com

# sub()
str = "Ironman is the strongest avenger!"
result = re.sub('Ironman',  'Thor', str)
print(result)

os modulecode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# os module is a powerful module in python
import os

# get current working directory
print(os.getcwd()) # prints 'G:\\workspace\\Python'

# change current working directory
os.chdir("G:\\workspace\\python\\learning")
print(os.getcwd()) # prints 'G:\\workspace\\python\\learning'

# list directories in the current working directory
print(os.listdir()) # prints ['built-ins', 'Lists', 'numpy', 'strings']

# list only files in the current working directory
files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
    print(f)

# create a directory in the current working directory
os.mkdir("dicts")
os.makedirs("dicts/nested-dicts")

# remove a directory in the current working directory
os.rmdir("dicts")
os.removedirs("dicts/nested-dicts")

# rename a file or directory
os.rename("Lists", "lists")

# stats of a file or directory
os.stat("lists")
# prints 'os.stat_result(st_mode=16895, st_ino=281474977861215, st_dev=4143122855, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1480252546, st_mtime=1480252546, st_ctime=1480252090)'

# traverse a directory tree
for dirpath, dirnames, filenames in os.walk("G:\\workspace\\python\\learning"):
    print("Current Path: ", dirpath)
    print("Directories: ", dirnames)
    print("Files: ", filenames)
    print()

'''
prints 
Current Path:  G:\workspace\python\learning
Directories:  ['Built-ins', 'lists', 'NumPy', 'Strings']
Files:  []

Current Path:  G:\workspace\python\learning\Built-ins
Directories:  []
Files:  ['evalu.py', 'input.py', 'zipped.py']

Current Path:  G:\workspace\python\learning\lists
Directories:  []
Files:  ['list_01.py', 'tuple_01.py']

Current Path:  G:\workspace\python\learning\NumPy
Directories:  []
Files:  ['ceilr.py', 'concatenate.py', 'eye_identity.py', 'flatten.py', 'math.py', 'mean_var_std.py', 'min_max.py', 'rev_array.py', 'sum_prod.py', 'zeros_ones.py']

Current Path:  G:\workspace\python\learning\Strings
Directories:  []
Files:  ['formatting.py']
'''

# check if a file exist
print(os.path.isfile("G:\\workspace\\python\\learning\\Strings\\formatting.py"))
# prints 'True'

# check if a directory exist
print(os.path.exists("G:\\workspace\\python\\learning\\Strings"))
print(os.path.isdir("G:\\workspace\\python\\learning\\Strings"))
# both prints 'True'

# accessing environment variable
print(os.environ.get("HOME"))
# prints 'C:\\Users\\Gogul Ilango'

sys modulecode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# sys module is used to parse input arguments given to a python file.
# this is used if you call a python script with arguments in command line.
import sys

firstarg  = ""
secondarg = ""
try:
    firstarg  = sys.argv[1]
    secondarg = sys.argv[2]
except:
    if (firstarg == ""):
        print("No first argument!")
    if (secondarg == ""):
        print("No second argument!")

# error text
sys.stderr.write("This is stderr text\n")
sys.stderr.flush()
sys.stdout.write("This is stdout text\n")

shutil modulecode

1
2
3
4
5
6
7
8
9
10
11
# shutil module is used for copying, moving, removing directory trees.
import shutil 

# copy file from one location to another
shutil.copyfile("/path/to/file_source", "path/to/file_destination")

# recursively copy entire directory tree from source to destination
shutil.copytree("source_dir", "destination_dir")

# recursively delete a directory tree
shutil.rmtree("/one/two/three")

OOP

Model real-world entities as software objects (having class as a blueprint) which have some data associated with them (variables) and can perform certain functions (methods).

Examples are

  • A person class with
    • variables: name, property, age, address
    • methods: walking, talking, running, swimming
  • An email class with
    • variables: recipients, subject, body
    • methods: add attachment, send, discard

Classescode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# create a class
class Customer(object):

    # init method is a must
    def __init__(self, name, age):
        self.name = name
        self.age  = age

    # a simple print method
    def print_customer(self):
        print("Customer: {}, Age: {}".format(self.name, self.age))

# define an instance
a = Customer("Gogul", "24")
a.print_customer() # prints "Customer: Gogul, Age: 24"

Class Variablescode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Customer(object):

    # this is a class variable
    raise_amount = 1.05
    num_of_custs = 0

    def __init__(self, name, age, pay):
        self.name = name
        self.age  = age
        self.pay  = pay

        Customer.num_of_custs += 1

    def apply_raise(self):
        print("Customer {} new pay is {}".format(self.name, float(self.pay) * self.raise_amount))

if __name__ == '__main__':
    # class variable not updated
    a = Customer("Gogul", "24", "5000")
    a.apply_raise() # prints Customer Gogul new pay is 5250.0

    # class variable updated
    b = Customer("Mahadevan", "25", "6000")
    b.raise_amount = 2.05
    b.apply_raise() # Customer Mahadevan new pay is 12299.999999999998

    # print dict of an instance
    print(a.__dict__) # prints {'name': 'Gogul', 'age': '24', 'pay': '5000'}

    # There are 2 customers
    print("There are {} customers".format(Customer.num_of_custs))

Inheritance

It is the process by which one class takes on the attributes and methods of another class. This inherited class is called child class. The class from which child class was inherited is called parent class.

Note: Child classes override or extend the attributes and behaviors of parent class i.e., child classes inherit all of the parent's attributes and behaviors but can also specify different functionality (attributes or behaviors) to follow.

Inheritancecode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# parent class
class Avenger:
    # initializer with instance attributes
    def __init__(self, name):
        self.name = name

    # instance method
    def slogan():
        print("We are here to protect the universe!")

# Child class inherited from Avenger class
class Ironman(Avenger):
    def change_suit(self, suit):
        self.suit = suit

    def fly(self, speed):
        print("Sir! You are now flying at {} km/h with my favorite {} suit!".format(speed, self.suit))

# Child class inherited from Avenger class
class Thor(Avenger):
    def change_weapon(self, weapon):
        self.weapon = weapon

    def slam(self, message):
        print("{} now use {}. {}".format(self.name, self.weapon, message))

# first object
ironman = Ironman("Robert Downey Jr")
ironman.change_suit("MARK XLVII")
ironman.fly(300)
# prints "Sir! You are now flying at 300 km/h with my favorite MARK XLVII suit!"

# second object
thor = Thor("Chris Hemsworth")
thor.change_weapon("StormBreaker")
thor.slam("Bring me Thanos!!!!!!!!!!")
# print "Chris Hemsworth now use StormBreaker. Bring me Thanos!!!!!!!!!!"

How to's

How to handle files?code

1
2
3
4
5
6
7
8
9
10
'''
four different methods (modes) to open a file
"r" - read; default mode; opens a file for reading, error if the file does not exist.
"a" - append; opens a file for appending, creates the file if it does not exist.
"w" - write; opens a file for writing, creates the file if it does not exist.
"x" - create; creates the file, returns an error if the file exist.

"t" - text; default/text mode
"b" - binary; binary mode
'''

How to read file line-by-line?code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# not the memory efficient way
filename = "entry_1.txt"
with open(filename) as f:
    data = f.readlines()
# remove whitespaces at end of each line
data = [x.strip() for x in data] 

# memory efficient way
filename = "entry_1.txt"
data = []
with open(filename) as f:
    for line in f:
        data.append(line)
# remove whitespaces at end of each line
data = [x.strip() for x in data]

How to write file line-by-line?code

1
2
3
4
5
l = ["pikachu", "charmander", "pidgeotto"]
fout = open("entry2.txt", "w")
for x in l:
    fout.write(x)
fout.close()

How to load json file?code

1
2
3
4
5
import json

file_input = "data.json"
with open(file_input) as data_file:    
    data = json.load(datafile)

How to check if list is empty?code

1
2
3
4
5
6
7
# method 1 
if not myList:
    print("list is empty")

# method 2
if len(myList) == 0:
    print("list is empty")

How to access index in for loop?code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
myList = ["a", "b", "c"]

# method 1
for idx, l in enumerate(myList):
    print(str(idx) + "-" + l)

# method 2
idx = 0
for l in myList:
    print(str(idx) + "-" + l)
    idx += 1

# both methods print
# 0-a 
# 1-b
# 2-c

How to sort a dictionary by key or value alphabetically?code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
a = {}
a["India"] = "Dhoni"
a["SouthAfrica"] = "ABD"
a["Australia"] = "Smith"

# sort dictionary based on 'key' alphabetically
for key in sorted(a.keys(), key=lambda x:x.lower()):
    print("{0} - {1}".format(key, a[key]))

# prints 
# Australia - Smith
# India - Dhoni
# SouthAfrica - ABD

# sort dictionary based on 'value' alphabetically
for key in sorted(a.keys(), key=lambda x:a[x]):
    print("{0} - {1}".format(key, a[key]))

# prints 
# SouthAfrica - ABD
# India - Dhoni
# Australia - Smith

How to call tcl procedure in python?code

1
2
3
4
5
6
# let's say you have a tcl file named 'test.tcl' with contents as below.
puts "Hello"
proc sum {a b} {
    set c [expr $a + $b]
    puts "Addition of $a and $b is $c"
}
1
2
3
4
5
6
7
8
9
# to call a tcl proc in python, we need 'tkinter' library which comes with python usually.
import tkinter
r = tkinter.Tk()
r.tk.eval("source test.tcl")
r.tk.eval("sum 10 20")

# prints 
# Hello
# Addition of 10 and 20 is 30

Resources

In case if you found something useful to add to this article or you found a bug in the code or would like to improve some points mentioned, feel free to write it down in the comments. Hope you found something useful here.