Python Quick Notes :: Part - 1


Bhaskar S 02/09/2013

Overview

Python is a modern general purpose programming language with the following characteristics:

Setup

Download and install the following software:

Hands-on With Python - I

Best way to learn any language is to get our hands dirty. So without much further ado lets get started.

Basic built-in scalar data types supported by Python:

Basic built-in functions (for basic data types) supported by Python:

Some of the special built-in operators (for numbers and strings) supported by Python:

The following is our first python program named sample-01.py:

sample-01.py
#
# Name: sample-01.py
#

# Basic data assignments

a = True
b = 65
c = -725
d = 1234567891
e = 2.5
f = 987654321.75
g = 3 + 4j
h = "This is a String"

# Print variables

print("a = ", a)
print("b = ", b)
print("c = ", c)
print("d = ", d)
print("e = ", e)
print("f = ", f)
print("g = ", g)
print("g (real) = ", g.real)
print("g (imag) = ", g.imag)
print("h = ", h)

# Multiple assignments

i, j, k = False, 0x375, 2.35e4

print("i = ", i)
print("j = ", j)
print("k = ", k)

# Swap

l = 25
m = 50

print("l (before) = ", l)
print("m (before) = ", m)

l, m = m, l

print("l (after) = ", l)
print("m (after) = ", m)

# Basic operations

n = m + l
o = d - e
p = g * e
q = d / c
r = d / e
s = d % b
t = m ** l

print("n = ", n)
print("o = ", o)
print("p = ", p)
print("q = ", q)
print("r = ", r)
print("s = ", s)
print("t = ", t)

# Basic built-in function(s)

print("abs(c) = ", abs(c))

print("chr(b) = ", chr(b))

print("eval('l+m') = ", eval('l+m'))

print("len(h) = ", len(h))

print("max(1, 2, 3, 4, 5) = ", max(1, 2, 3, 4, 5))

print("min(-1, -2, -3, -4, -5) = ", min(-1, -2, -3, -4, -5))

print("round(f/e) = ", round(f/e))

print("Type of a: ", type(a))
print("Type of d: ", type(d))
print("Type of e: ", type(e))
print("Type of g: ", type(g))
print("Type of h: ", type(h))

# Prompt for string

text = input("Enter some text: ")

# Prompt for number

number = eval(input("Enter some number: "))

# Print text length

print("len(text) = ", len(text))

# String indexing and slicing

print("text[0] = ", text[0])
print("text[-1] = ", text[-1])
print("text[1:5] = ", text[1:5])
print("text[2:] = ", text[2:])
print("text[:3] = ", text[:3])

# String operations

u = "hello" + " " + "python"
v = "python" * 3

print("u = ", u)
print("v = ", v)

print("String h = '%s' and integer b = %d" % (h, b))

NOTE :: Python program files have the extension ".py"

Execute the following command:

python sample-01.py

The following is the output:

Output (sample-01.py)

a =  True
b =  65
c =  -725
d =  1234567891
e =  2.5
f =  987654321.75
g =  (3+4j)
g (real) =  3.0
g (imag) =  4.0
h =  This is a String
i =  False
j =  885
k =  23500.0
l (before) =  25
m (before) =  50
l (after) =  50
m (after) =  25
n =  75
o =  1234567888.5
p =  (7.5+10j)
q =  -1702853
r =  493827156.4
s =  11
t =  7888609052210118054117285652827862296732064351090230047702789306640625
abs(c) =  725
chr(b) =  A
eval('l+m') =  75
len(h) =  16
max(1, 2, 3, 4, 5) =  5
min(-1, -2, -3, -4, -5) =  -5
round(f/e) =  395061729.0
Type of a:  <type 'bool'>
Type of d:  <type 'int'>
Type of e:  <type 'float'>
Type of g:  <type 'complex'>
Type of h:  <type 'str'>
Enter some text: Python
Enter some number: 1275
len(text) =  6
text[0] =  P
text[-1] =  n
text[1:5] =  ytho
text[2:] =  thon
text[:3] =  Pyt
u =  hello python
v =  pythonpythonpython
String h = 'This is a String' and integer b = 65

Built-in string methods supported by Python:

The following is the python program named sample-02.py:

sample-02.py
#
# Name: sample-02.py
#

# Built-in string method(s)

str1 = "welcome to python"
str2 = "   Hello Python   "

print("str1 = '%s', str2 = '%s'" % (str1, str2))

print("str1.capitalize() = %s" % (str1.capitalize()))
print("str1.title() = %s" % (str1.title()))

print("str1.startswith('welcome') = %s" % (str1.startswith("welcome")))
print("str2.startswith('welcome') = %s" % (str2.startswith("welcome")))

print("str1.endswith('python') = %s" % (str1.endswith("python")))
print("str2.endswith('python') = %s" % (str2.endswith("python")))

print("str1.find('P') = %d" % (str1.find("P")))
print("str2.find('P') = %d" % (str2.find("P")))

print("str1.rfind('o') = %d" % (str1.rfind("o")))
print("str2.rfind('c') = %d" % (str2.rfind("c")))

print("str2.lstrip() = '%s'" % (str2.lstrip()))
print("str2.rstrip() = '%s'" % (str2.rstrip()))
print("str2.strip() = '%s'" % (str2.strip()))

print("str2.lower() = '%s'" % (str2.lower()))
print("str1.upper() = '%s'" % (str1.upper()))

print("str2.replace('Hello', 'COOL') = '%s'" % (str2.replace("Hello", "COOL")))

Execute the following command:

python sample-02.py

The following is the output:

Output (sample-02.py)

str1 = 'welcome to python', str2 = '   Hello Python   '
str1.capitalize() = Welcome to python
str1.title() = Welcome To Python
str1.startswith('welcome') = True
str2.startswith('welcome') = False
str1.endswith('python') = True
str2.endswith('python') = False
str1.find('P') = -1
str2.find('P') = 9
str1.rfind('o') = 15
str2.rfind('c') = -1
str2.lstrip() = 'Hello Python   '
str2.rstrip() = '   Hello Python'
str2.strip() = 'Hello Python'
str2.lower() = '   hello python   '
str1.upper() = 'WELCOME TO PYTHON'
str2.replace('Hello', 'COOL') = '   COOL Python   '

Simple control flow structures supported by Python:

NOTE :: The logical operators in Python are and, or, not

The following is the python program named sample-03.py:

sample-03.py
#
# Name: sample-03.py
#

# Simple if-else

text = input("Enter some text: ")
if len(text) <= 10:
    print("You entered a short text")
else:
    print("Text length: ", len(text))

# Simple if-elif-else

number = eval(input("Enter number between 1 to 10: "))
if number <= 0:
    print("Number less than 1")
elif number > 10:
    print("Number greater than 10")
else:
    print("Number = ", number)

# Logical operators

if len(text) <= 5 and number <= 5:
    print("Less than 5")
else:
    print("Not less than 5")

if len(text) > 5 or number > 5:
    print("Either is greater than 5")
else:
    print("Neither is greater than 5")

if not number > 5:
    print("Number less than or equal to 5")

# Simple while

counter = 0
while counter < number:
    print("counter (while): ", counter)
    counter = counter + 1

# Simple for

for counter in range(0, number):
    print("counter (for): ", counter)

ch = 0
for t in text:
    print("t (", ch, ") =", t)
    ch += 1

Execute the following command:

python sample-03.py

The following is the output:

Output (sample-03.py)

Enter some text: Hello Python
Text length:  12
Enter number between 1 to 10: 7
Number =  7
Not less than 5
Either is greater than 5
counter (while):  0
counter (while):  1
counter (while):  2
counter (while):  3
counter (while):  4
counter (while):  5
counter (while):  6
counter (for):  0
counter (for):  1
counter (for):  2
counter (for):  3
counter (for):  4
counter (for):  5
counter (for):  6
t ( 0 ) = H
t ( 1 ) = e
t ( 2 ) = l
t ( 3 ) = l
t ( 4 ) = o
t ( 5 ) =  
t ( 6 ) = P
t ( 7 ) = y
t ( 8 ) = t
t ( 9 ) = h
t ( 10 ) = o
t ( 11 ) = n

Complex built-in data types supported by Python:

Basic built-in functions (for complex data types) supported by Python:

Some of the special built-in operators (for lists and tuples) supported by Python:

Built-in list methods supported by Python:

The following is the python program named sample-04.py:

sample-04.py
#
# Name: sample-04.py
#

# All about Lists

list = [9, 1, 8, 2, 7, 3, 5, 4]

# Basics

print("type(list) = ", type(list))
print("list = ", list)
print("len(list) = ", len(list))
print("max(list) = ", max(list))
print("min(list) = ", min(list))

# List indexing and slicing

print("list[0] = ", list[0])
print("list[1:3] = ", list[1:3])
print("list[2:] = ", list[2:])
print("list[:3] = ", list[:3])

# List is mutable

print("list (before) = ", list)

list[1] = 0
list[3] = 1
list[5] = 2
list[7] = 3

print("list (after) = ", list)

# List can contain anything

list2 = [1, 2.5, "Python"]

print("list2 = ", list2)

# List operations

print("[1, 2, 3] * 3 = ", [1, 2, 3] * 3)

list3 = list2 + ['A', -3, 3+5j]

print("list3 = ", list3)

print("-3 in list3 = ", -3 in list3)
print("5 in list3 = ", 5 in list3)

for x in list2:
    print("list2: x = ", x)

list2.append(2e-2)

print("list2 = ", list2)

list2.extend(list)

print("list2 = ", list2)

print("list2.count(1) = ", list2.count(1))

print("list2.index(9) = ", list2.index(9))

list2.insert(5, 100)

print("list2 (after insert) = ", list2)

list2.pop()

print("list2 (after pop) = ", list2)

list2.pop(3)

print("list2 (after pop 3) = ", list2)

list3.remove(3+5j)

print("list3 (after remove 3+5j) = ", list3)

list2.reverse()

print("list2 (after reverse) = ", list2)

list.sort()

print("list (after sort) = ", list)

Execute the following command:

python sample-04.py

The following is the output:

Output (sample-04.py)

type(list) =  <type 'list'>
list =  [9, 1, 8, 2, 7, 3, 5, 4]
len(list) =  8
max(list) =  9
min(list) =  1
list[0] =  9
list[1:3] =  [1, 8]
list[2:] =  [8, 2, 7, 3, 5, 4]
list[:3] =  [9, 1, 8]
list (before) =  [9, 1, 8, 2, 7, 3, 5, 4]
list (after) =  [9, 0, 8, 1, 7, 2, 5, 3]
list2 =  [1, 2.5, 'Python']
[1, 2, 3] * 3 =  [1, 2, 3, 1, 2, 3, 1, 2, 3]
list3 =  [1, 2.5, 'Python', 'A', -3, (3+5j)]
-3 in list3 =  True
5 in list3 =  False
list2: x =  1
list2: x =  2.5
list2: x =  Python
list2 =  [1, 2.5, 'Python', 0.02]
list2 =  [1, 2.5, 'Python', 0.02, 9, 0, 8, 1, 7, 2, 5, 3]
list2.count(1) =  2
list2.index(9) =  4
list2 (after insert) =  [1, 2.5, 'Python', 0.02, 9, 100, 0, 8, 1, 7, 2, 5, 3]
list2 (after pop) =  [1, 2.5, 'Python', 0.02, 9, 100, 0, 8, 1, 7, 2, 5]
list2 (after pop 3) =  [1, 2.5, 'Python', 9, 100, 0, 8, 1, 7, 2, 5]
list3 (after remove 3+5j) =  [1, 2.5, 'Python', 'A', -3]
list2 (after reverse) =  [5, 2, 7, 1, 8, 0, 100, 9, 'Python', 2.5, 1]
list (after sort) =  [0, 1, 2, 3, 5, 7, 8, 9]

Built-in tuple methods supported by Python:

The following is the python program named sample-05.py:

sample-05.py
#
# Name: sample-05.py
#

# All about Tuples

tuple = (9, 1, 8, 2, 7, 3, 5, 4)

# Basics

print("type(tuple) = ", type(tuple))
print("tuple = ", tuple)
print("len(tuple) = ", len(tuple))
print("max(tuple) = ", max(tuple))
print("min(tuple) = ", min(tuple))

# Tuple indexing and slicing

print("tuple[0] = ", tuple[0])
print("tuple[1:3] = ", tuple[1:3])
print("tuple[2:] = ", tuple[2:])
print("tuple[:3] = ", tuple[:3])

# Tuple can contain anything

tuple2 = (1, 2.5, "Python")

print("tuple2 = ", tuple2)

# Tuple operations

print("(1, 2, 3) * 3 = ", (1, 2, 3) * 3)

tuple3 = tuple2 + ('A', -3, 3+5j)

print("tuple3 = ", tuple3)

print("-3 in tuple3 = ", -3 in tuple3)
print("5 in tuple3 = ", 5 in tuple3)

for x in tuple2:
    print("tuple2: x = ", x)

print("tuple2.count(1) = ", tuple2.count(1))

print("tuple2.index(2.5) = ", tuple2.index(2.5))

Execute the following command:

python sample-05.py

The following is the output:

Output (sample-05.py)

type(tuple) =  <type 'tuple'>
tuple =  (9, 1, 8, 2, 7, 3, 5, 4)
len(tuple) =  8
max(tuple) =  9
min(tuple) =  1
tuple[0] =  9
tuple[1:3] =  (1, 8)
tuple[2:] =  (8, 2, 7, 3, 5, 4)
tuple[:3] =  (9, 1, 8)
tuple2 =  (1, 2.5, 'Python')
(1, 2, 3) * 3 =  (1, 2, 3, 1, 2, 3, 1, 2, 3)
tuple3 =  (1, 2.5, 'Python', 'A', -3, (3+5j))
-3 in tuple3 =  True
5 in tuple3 =  False
tuple2: x =  1
tuple2: x =  2.5
tuple2: x =  Python
tuple2.count(1) =  1
tuple2.index(2.5) =  1

Some of the special built-in operators (for dict) supported by Python:

Built-in dict methods supported by Python:

The following is the python program named sample-06.py:

sample-06.py
#
# Name: sample-06.py
#

# All about Dict

dict = { 'a': 5, 'b': 10, 'c': 15, 'd': 20 }

# Basics

print("type(dict) = ", type(dict))
print("dict = ", dict)
print("len(dict) = ", len(dict))

print("dict['b'] = ", dict['b'])

dict['b'] = 25

print("dict['b'] (after update) = ", dict['b'])

# Dict operations

keys = list(dict.keys())

print("List of keys = ", keys)

values = list(dict.values())

print("List of values = ", values)

print("dict.get('c') = ", dict.get('c'))

print("dict.get('x', -1) = ", dict.get('x', -1))

print("dict.has_key('c') = ", 'c' in dict)
print("dict.has_key('x') = ", 'x' in dict)

list = list(dict.items())

print("List of (key, value) tuples = ", list)

dict.clear()

print("dict (after clear) = ", dict)

Execute the following command:

python sample-06.py

The following is the output:

Output (sample-06.py)

type(dict) =  <type 'dict'>
dict =  {'a': 5, 'c': 15, 'b': 10, 'd': 20}
len(dict) =  4
dict['b'] =  10
dict['b'] (after update) =  25
List of keys =  ['a', 'c', 'b', 'd']
List of values =  [5, 15, 25, 20]
dict.get('c') =  15
dict.get('x', -1) =  -1
dict.has_key('c') =  True
dict.has_key('x') =  False
List of (key, value) tuples =  [('a', 5), ('c', 15), ('b', 25), ('d', 20)]
dict (after clear) =  {}