A gentle introduction to Python

Ramanathan

1. Datatypes

1.1 Primitive datatypes

1.1.1 Integer

In [1]:
x = 100
x
Out[1]:
100

1.1.2 String

In [2]:
s = "Hello" + " World"
s
Out[2]:
'Hello World'

1.1.3 Float

In [3]:
pi = 3.1415
type(pi)
Out[3]:
float

1.1.4 Boolean

In [19]:
i = 10
j = 20
isGreater = i > 20
isGreater
Out[19]:
False

1.1.5 None

In [23]:
m = None # null value
print(m)
type(m)
None
Out[23]:
NoneType

1.2 Structured Datatypes

1.2.1 List - Arrays [ ]

In [5]:
hetrogeneous_array = ["Apple", 100, 6.023]
print('hetrogeneous_array =', hetrogeneous_array) # Use this for printing in Python
type(hetrogeneous_array)
hetrogeneous_array = ['Apple', 100, 6.023]
Out[5]:
list
In [6]:
hetrogeneous_array.append(40) ## Add new items to an array

print(hetrogeneous_array)
['Apple', 100, 6.023, 40]
In [7]:
hetrogeneous_array.__dir__()
Out[7]:
['__repr__',
 '__hash__',
 '__getattribute__',
 '__lt__',
 '__le__',
 '__eq__',
 '__ne__',
 '__gt__',
 '__ge__',
 '__iter__',
 '__init__',
 '__len__',
 '__getitem__',
 '__setitem__',
 '__delitem__',
 '__add__',
 '__mul__',
 '__rmul__',
 '__contains__',
 '__iadd__',
 '__imul__',
 '__new__',
 '__reversed__',
 '__sizeof__',
 'clear',
 'copy',
 'append',
 'insert',
 'extend',
 'pop',
 'remove',
 'index',
 'count',
 'reverse',
 'sort',
 '__doc__',
 '__str__',
 '__setattr__',
 '__delattr__',
 '__reduce_ex__',
 '__reduce__',
 '__subclasshook__',
 '__init_subclass__',
 '__format__',
 '__dir__',
 '__class__']

1.2.2 Tuple ( )

In [8]:
tpl = ('Ram', 40, 1000)
tpl
Out[8]:
('Ram', 40, 1000)
In [9]:
tpl.__dir__()
## Tuple has no append function - so cannot add new elements to this later
Out[9]:
['__repr__',
 '__hash__',
 '__getattribute__',
 '__lt__',
 '__le__',
 '__eq__',
 '__ne__',
 '__gt__',
 '__ge__',
 '__iter__',
 '__len__',
 '__getitem__',
 '__add__',
 '__mul__',
 '__rmul__',
 '__contains__',
 '__new__',
 '__getnewargs__',
 'index',
 'count',
 '__doc__',
 '__str__',
 '__setattr__',
 '__delattr__',
 '__init__',
 '__reduce_ex__',
 '__reduce__',
 '__subclasshook__',
 '__init_subclass__',
 '__format__',
 '__sizeof__',
 '__dir__',
 '__class__']

1.2.3 Named Tuple

should import the library

In [10]:
from collections import namedtuple

empl_list = []

nt = namedtuple( 'Employee', ['name', 'age', 'salary']);

empl_list.append ( nt._make(tpl) ) ## tpl from the above cell

new_emp = ('Adam', 25, 2000)
empl_list.append ( nt._make(new_emp) )

print( empl_list )
[Employee(name='Ram', age=40, salary=1000), Employee(name='Adam', age=25, salary=2000)]

1.2.4 Set { }

In [11]:
rainbow = { 'violet', 'indigo', 'blue', 'green', 'yellow', 'orange' }
print(rainbow)
rainbow.add('red')
print(rainbow)
rainbow.add('something') # add something once
rainbow.add('something') # add something twice
rainbow.add('something') # add something thrice
print(rainbow)
{'orange', 'blue', 'green', 'yellow', 'indigo', 'violet'}
{'red', 'orange', 'blue', 'green', 'yellow', 'indigo', 'violet'}
{'red', 'orange', 'blue', 'green', 'something', 'yellow', 'indigo', 'violet'}
In [12]:
rainbow.discard('something')

# Unfortunately there is no ordered set. You have to implement your own ordered set

1.2.5 Dictionary { : }

In [13]:
periodic_table = {
    "elements": [
        {
            "name": "Hydrogen", 
            "atomic_mass": 1.008, 
            "number": 1, 
            "phase": "Gas"
        }, 
        {
            "name": "Helium", 
            "atomic_mass": 4.0026022, 
            "number": 2, 
            "phase": "Gas"
        }
    ]
}

type(periodic_table)
Out[13]:
dict
In [14]:
print( periodic_table['elements'][1]['name'] ) # Access an element inside the dictionary tree
print( periodic_table['elements'][1]['number'] ) # Access an element inside the dictionary tree

# print( 'Elements map = ' + periodic_table['elements'] ) ## error without str because + cannot convert to string
# print( 'Elements map = ' + str(periodic_table['elements']) )
Helium
2

2. Control statements

(and indentation rules)

2.1 Conditional statement

2.1.1 If condition

In [15]:
print('Please input a number from 1 to 5: ')
user_ip = input()
my_num = int(user_ip)

if my_num == 1:
    print('You keyed in One')

if my_num == 2:
    print('You keyed in Two')

if my_num == 3:
    print('You keyed in Three')

if my_num == 4:
    print('You keyed in Four')

if my_num == 5:
    print('You keyed in Five')
Please input a number from 1 to 5: 
3
You keyed in Three

2.1.2 If - Else statement

In [2]:
print('Please select a fruit: ')
print(' 1 - Orange ')
print(' 2 - Apple ')

user_ip = input()

my_num = int(user_ip)

if my_num == 1:
    print(' You probably like Oranges ')
elif my_num == 2:
    print(' You probably like Apples ')
else:
    print(' You probably don\'t know English')
Please select a fruit: 
 1 - Orange 
 2 - Apple 
1
 You probably like Oranges 

2.2 Repetition statement

2.2.1 For loop

In [17]:
print(rainbow)
print('=================================================================')

for color in rainbow:
    print(color)
print('=================================================================')
for idx, color in enumerate(rainbow):
    print(idx, ' - ', color)
{'red', 'orange', 'blue', 'green', 'yellow', 'indigo', 'violet'}
=================================================================
red
orange
blue
green
yellow
indigo
violet
=================================================================
0  -  red
1  -  orange
2  -  blue
3  -  green
4  -  yellow
5  -  indigo
6  -  violet

2.2.2 While loops

In [18]:
i = 1
while i < 6:
  print(i)
  i += 1    ## Remember to do this incremental operation. Else the program will go to an infinite loop
1
2
3
4
5