# Python Examples Set 3

```Example 1
print('an Ashish Ranjan presentation')

Output
an Ashish Ranjan presentation

```

```Example 2
# This program adds two numbers provided by the user
# Store input numbers
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')

sum = int(num1) + int(num2)

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

@IDLE
Enter first number: 23
Enter second number: 47
The sum of 23 and 47 is 70

```

```Example 3
# Find square root of real or complex numbers
import cmath
num = eval(raw_input('Enter a number (real or complex-e.g. 64+64j): '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))

@IDLE
Enter a number (real or complex-e.g. 64+64j): 64+64j
The square root of (64+64j) is 8.789+3.641j

```

```Example 4
# area of triangle
# Heron's formula (Hero's formula)
while True:
try:
a = float(raw_input('Enter first side: '))
b = float(raw_input('Enter second side: '))
c = float(raw_input('Enter third side: '))
except:
print "Something went wrong"
continue

if a<=0 or b<=0 or c<=0:
print "Something went wrong"
continue

if (a+b>c) and (b+c>a) and (c+a>b):
break
else:
print 'Sum of any 2 sides of a triangle must be greater than the measure of the third side.'

# calculate the semi-perimeter
s = (a + b + c) / 2

# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

@IDLE
Enter first side: a
Something went wrong
Enter first side: 6
Enter second side: 9
Enter third side: -8
Something went wrong
Enter first side: 6
Enter second side: 6
Enter third side: 6
The area of the triangle is 15.59

```

```Example 5
# Solve the quadratic equation ax**2 + bx + c = 0
import cmath

a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant
d = (b**2) - (4*a*c)

# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(sol1,sol2))

@IDLE
Enter a: 2
Enter b: 3
Enter c: 4
The solution are (-0.75-1.19895788083j) and (-0.75+1.19895788083j)

```

```Example 6
# swap two variables
x = 15
y = 35

print 'Method 1'
print('Before swapping x = {} and y = {}'.format(x,y))
temp = x
x = y
y = temp
print('After swapping x = {} and y = {}'.format(x,y))

print '\nMethod 2'
print('Before swapping x = {} and y = {}'.format(x,y))
x,y = y,x
print('After swapping x = {} and y = {}'.format(x,y))

print '\nMethod 3'
print('Before swapping x = {} and y = {}'.format(x,y))
x = x + y
y = x - y
x = x - y
print('After swapping x = {} and y = {}'.format(x,y))

print '\nMethod 4'
print('Before swapping x = {} and y = {}'.format(x,y))
x = x * y
y = x / y
x = x / y
print('After swapping x = {} and y = {}'.format(x,y))

print '\nMethod 5'
print('Before swapping x = {} and y = {}'.format(x,y))
x = x ^ y
y = x ^ y
x = x ^ y
print('After swapping x = {} and y = {}'.format(x,y))

@IDLE
Method 1
Before swapping x = 15 and y = 35
After swapping x = 35 and y = 15

Method 2
Before swapping x = 35 and y = 15
After swapping x = 15 and y = 35

Method 3
Before swapping x = 15 and y = 35
After swapping x = 35 and y = 15

Method 4
Before swapping x = 35 and y = 15
After swapping x = 15 and y = 35

Method 5
Before swapping x = 15 and y = 35
After swapping x = 35 and y = 15

```

```Example 7
# generate a random number
import random

guessedNumber = 0
while True:
try:
guessedNumber = int(raw_input("Guess a random number (0-20)"))
except:
print "Something went wrong"
continue
i = 0
flag = False
print "10 random numbers"
while True:
randomNumber = random.randint(0,20)
i += 1
if i>=9:
break
print randomNumber,
if randomNumber == guessedNumber:
flag = True
if flag == True:
print "\nYou guessed it right."
else:
print "\nWrong guess."
try:
again = raw_input("\nTry your luck again (0 to quit) ???  ")
if int(again) == 0:
break
except:
continue

@IDLE
Guess a random number (0-20)4
10 random numbers
9 14 7 20 15 11 6 9
Wrong guess.

Try your luck again (0 to quit) ???
Guess a random number (0-20)4
10 random numbers
17 2 9 7 5 8 14 13
Wrong guess.

Try your luck again (0 to quit) ???
Guess a random number (0-20)4
10 random numbers
20 14 11 14 5 16 14 15
Wrong guess.

Try your luck again (0 to quit) ???
Guess a random number (0-20)4
10 random numbers
4 6 4 18 9 11 11 18
You guessed it right.

Try your luck again (0 to quit) ???
Guess a random number (0-20)4
10 random numbers
11 4 3 14 2 17 17 6
You guessed it right.

Try your luck again (0 to quit) ???  0
>>>

```

```Example 8
# convert kilometers into miles
# convert temperature in celsius to fahrenheit

# take input from the user
kilometers = float(input('How many kilometers?: '))
celsius = float(input('Enter degree Celsius: '))

# conversion factor
conv_fac = 0.621371
fahrenheit = (celsius * 1.8) + 32

# calculate miles
miles = kilometers * conv_fac
print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))

@IDLE
How many kilometers?: 5.5
Enter degree Celsius: 37.5
5.500 kilometers is equal to 3.418 miles
37.5 degree Celsius is equal to 99.5 degree Fahrenheit

```

```Example 9
# check if the number is positive or negative or zero

num = 0
while True:
try:
num = float(raw_input("Enter a number: "))
break
except:
print "Something went wrong"
continue
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

@IDLE
>>>
================ RESTART: F:\Python Programs\set 3\example.py ================
Enter a number: 0
Zero
>>>
================ RESTART: F:\Python Programs\set 3\example.py ================
Enter a number: 1
Positive number
>>>
================ RESTART: F:\Python Programs\set 3\example.py ================
Enter a number: -2
Negative number
>>>
================ RESTART: F:\Python Programs\set 3\example.py ================
Enter a number: s
Something went wrong
Enter a number: 0
Zero
>>>

```

```Example 10
# check if the input number is odd or even.
num = 0
while True:
try:
num = int(raw_input("Enter a number: "))
break
except:
print 'Something went wrong'
continue
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

@IDLE
Enter a number: s
Something went wrong
Enter a number: 23
23 is Odd

```

```Example 11
# input year is a leap year or not
year = 0
while True:
try:
year = int(raw_input("Enter a year: "))
break
except:
print 'Something went wrong'
continue
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

@IDLE
Enter a year: ash
Something went wrong
Enter a year: 2014
2014 is not a leap year

```

```Example 12
# Python program to find the largest number among the three input numbers

num1 = 0
num2 = 0
num3 = 0
while True:
try:
num1 = float(raw_input("Enter first number: "))
break
except:
print "Something went wrong"
continue
while True:
try:
num2 = float(raw_input("Enter second number: "))
break
except:
print "Something went wrong"
continue
while True:
try:
num3 = float(raw_input("Enter third number: "))
break
except:
print "Something went wrong"
continue
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3

print("The largest number is",largest)

@IDLE
Enter first number: f
Something went wrong
Enter first number: 23
Enter second number: 34
Enter third number: -2
('The largest number is', 34.0)

```

```Example 13
# prime numbers
limit = 30
print "Sieve of Eratosthenes"
def primes_sieve(limit):
limitn = limit+1
not_prime = set()
primes = []

for i in range(2, limitn):
if i in not_prime:
continue

for f in range(i*2, limitn, i):

primes.append(i)

return primes
print primes_sieve(30)

print
for num in range(1,limit):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print num,": NOT PRIME -> ",
print i, "*", num//i, "=", num
break
else:
print num,": PRIME"
else:
print(num,"is not a prime number")

@IDLE
Sieve of Eratosthenes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

(1, 'is not a prime number')
2 : PRIME
3 : PRIME
4 : NOT PRIME ->  2 * 2 = 4
5 : PRIME
6 : NOT PRIME ->  2 * 3 = 6
7 : PRIME
8 : NOT PRIME ->  2 * 4 = 8
9 : NOT PRIME ->  3 * 3 = 9
10 : NOT PRIME ->  2 * 5 = 10
11 : PRIME
12 : NOT PRIME ->  2 * 6 = 12
13 : PRIME
14 : NOT PRIME ->  2 * 7 = 14
15 : NOT PRIME ->  3 * 5 = 15
16 : NOT PRIME ->  2 * 8 = 16
17 : PRIME
18 : NOT PRIME ->  2 * 9 = 18
19 : PRIME
20 : NOT PRIME ->  2 * 10 = 20
21 : NOT PRIME ->  3 * 7 = 21
22 : NOT PRIME ->  2 * 11 = 22
23 : PRIME
24 : NOT PRIME ->  2 * 12 = 24
25 : NOT PRIME ->  5 * 5 = 25
26 : NOT PRIME ->  2 * 13 = 26
27 : NOT PRIME ->  3 * 9 = 27
28 : NOT PRIME ->  2 * 14 = 28
29 : PRIME

```

```Example 14
# factorial
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 0
while True:
try:
num = int(raw_input("Enter a number: "))
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
continue
break
except:
print "Something went wrong"
continue

factorial = 1
if num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print "Method 1 gives: factorial of ", num, "is", factorial
print "Method 2 gives: factorial of ", num, "is", recur_factorial(num)

@IDLE
Enter a number: -2
Sorry, factorial does not exist for negative numbers
Enter a number: 7
Method 1 gives: factorial of  7 is 5040
Method 2 gives: factorial of  7 is 5040

```

```Example 15
# multiplication table (from 1 to 20)
num = 5
for num in range(1,21):
for i in range(1,11):
print num, ' x ', i, ' = ', num*i
print

@IDLE
1  x  1  =  1
1  x  2  =  2
1  x  3  =  3
1  x  4  =  4
1  x  5  =  5
1  x  6  =  6
1  x  7  =  7
1  x  8  =  8
1  x  9  =  9
1  x  10  =  10

2  x  1  =  2
2  x  2  =  4
2  x  3  =  6
2  x  4  =  8
2  x  5  =  10
2  x  6  =  12
2  x  7  =  14
2  x  8  =  16
2  x  9  =  18
2  x  10  =  20

3  x  1  =  3
3  x  2  =  6
3  x  3  =  9
3  x  4  =  12
3  x  5  =  15
3  x  6  =  18
3  x  7  =  21
3  x  8  =  24
3  x  9  =  27
3  x  10  =  30

4  x  1  =  4
4  x  2  =  8
4  x  3  =  12
4  x  4  =  16
4  x  5  =  20
4  x  6  =  24
4  x  7  =  28
4  x  8  =  32
4  x  9  =  36
4  x  10  =  40

5  x  1  =  5
5  x  2  =  10
5  x  3  =  15
5  x  4  =  20
5  x  5  =  25
5  x  6  =  30
5  x  7  =  35
5  x  8  =  40
5  x  9  =  45
5  x  10  =  50

6  x  1  =  6
6  x  2  =  12
6  x  3  =  18
6  x  4  =  24
6  x  5  =  30
6  x  6  =  36
6  x  7  =  42
6  x  8  =  48
6  x  9  =  54
6  x  10  =  60

7  x  1  =  7
7  x  2  =  14
7  x  3  =  21
7  x  4  =  28
7  x  5  =  35
7  x  6  =  42
7  x  7  =  49
7  x  8  =  56
7  x  9  =  63
7  x  10  =  70

8  x  1  =  8
8  x  2  =  16
8  x  3  =  24
8  x  4  =  32
8  x  5  =  40
8  x  6  =  48
8  x  7  =  56
8  x  8  =  64
8  x  9  =  72
8  x  10  =  80

9  x  1  =  9
9  x  2  =  18
9  x  3  =  27
9  x  4  =  36
9  x  5  =  45
9  x  6  =  54
9  x  7  =  63
9  x  8  =  72
9  x  9  =  81
9  x  10  =  90

10  x  1  =  10
10  x  2  =  20
10  x  3  =  30
10  x  4  =  40
10  x  5  =  50
10  x  6  =  60
10  x  7  =  70
10  x  8  =  80
10  x  9  =  90
10  x  10  =  100

11  x  1  =  11
11  x  2  =  22
11  x  3  =  33
11  x  4  =  44
11  x  5  =  55
11  x  6  =  66
11  x  7  =  77
11  x  8  =  88
11  x  9  =  99
11  x  10  =  110

12  x  1  =  12
12  x  2  =  24
12  x  3  =  36
12  x  4  =  48
12  x  5  =  60
12  x  6  =  72
12  x  7  =  84
12  x  8  =  96
12  x  9  =  108
12  x  10  =  120

13  x  1  =  13
13  x  2  =  26
13  x  3  =  39
13  x  4  =  52
13  x  5  =  65
13  x  6  =  78
13  x  7  =  91
13  x  8  =  104
13  x  9  =  117
13  x  10  =  130

14  x  1  =  14
14  x  2  =  28
14  x  3  =  42
14  x  4  =  56
14  x  5  =  70
14  x  6  =  84
14  x  7  =  98
14  x  8  =  112
14  x  9  =  126
14  x  10  =  140

15  x  1  =  15
15  x  2  =  30
15  x  3  =  45
15  x  4  =  60
15  x  5  =  75
15  x  6  =  90
15  x  7  =  105
15  x  8  =  120
15  x  9  =  135
15  x  10  =  150

16  x  1  =  16
16  x  2  =  32
16  x  3  =  48
16  x  4  =  64
16  x  5  =  80
16  x  6  =  96
16  x  7  =  112
16  x  8  =  128
16  x  9  =  144
16  x  10  =  160

17  x  1  =  17
17  x  2  =  34
17  x  3  =  51
17  x  4  =  68
17  x  5  =  85
17  x  6  =  102
17  x  7  =  119
17  x  8  =  136
17  x  9  =  153
17  x  10  =  170

18  x  1  =  18
18  x  2  =  36
18  x  3  =  54
18  x  4  =  72
18  x  5  =  90
18  x  6  =  108
18  x  7  =  126
18  x  8  =  144
18  x  9  =  162
18  x  10  =  180

19  x  1  =  19
19  x  2  =  38
19  x  3  =  57
19  x  4  =  76
19  x  5  =  95
19  x  6  =  114
19  x  7  =  133
19  x  8  =  152
19  x  9  =  171
19  x  10  =  190

20  x  1  =  20
20  x  2  =  40
20  x  3  =  60
20  x  4  =  80
20  x  5  =  100
20  x  6  =  120
20  x  7  =  140
20  x  8  =  160
20  x  9  =  180
20  x  10  =  200

```

```Example 16
# Fibonacci
def fib1(n):
if n == 1 or n== 2:
return 1
return fib1(n-1) + fib1(n-2)

def fib2(n):
a,b = 1, 1
for i in range(n-1):
a, b = b, a+b
return a

def fib3():
a, b = 1, 1
while True:
yield a
a, b = b, a+b

num = 0
while True:
try:
num = int(raw_input("Enter number of terms: "))
if num < 0:
print("Sorry, fibonacci does not exist for negative numbers")
continue
break
except:
print "Something went wrong"
continue

print "function 1 gives:"
for i in range(1,num+1):
print fib1(i),

print "\n\nfunction 2 gives:"
for i in range(1,num+1):
print fib2(i),

print "\n\nfunction 3 gives:"
n = 0
for i in fib3():
if n>=num:
break
print i,
n += 1

@IDLE
Enter number of terms: ash
Something went wrong
Enter number of terms: -a
Something went wrong
Enter number of terms: -13
Sorry, fibonacci does not exist for negative numbers
Enter number of terms: 13
function 1 gives:
1 1 2 3 5 8 13 21 34 55 89 144 233

function 2 gives:
1 1 2 3 5 8 13 21 34 55 89 144 233

function 3 gives:
1 1 2 3 5 8 13 21 34 55 89 144 233

```

```Example 17
# Armstrong number
lower = 0
while True:
try:
lower = int(input("Enter lower range: "))
if lower <= 0:
print "Something went wrong"
continue
break
except:
print "Something went wrong"
continue
upper = 0
while True:
try:
upper = int(input("Enter upper range: "))
if upper <= lower :
print "Something went wrong"
continue
break
except:
print "Something went wrong"
continue
print "\nArmstrong numbers between ", lower, " to ", upper, " are:"
for num in range(lower,upper + 1):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print num,

@IDLE
Enter lower range: 1
Enter upper range: 9999

Armstrong numbers between  1  to  9999 are:
1 153 370 371 407

```

```Example 18
# sum of natural numbers up to n
num = 1
while True:
try:
num = int(raw_input("Enter last number: "))
if num < 1:
print "Something went wrong"
continue
break
except:
print "Something went wrong"
continue

temp = num
sum = 0
while(num > 0):
sum += num
num -= 1

def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)

print "Method 1 gives"
print "The sum is: ", sum

print "Method 2 gives"
print "The sum is: ", temp * (temp + 1) / 2

print "Method 3 gives"
print "The sum is: ", recur_sum(temp)

@IDLE
Enter last number: 34
Method 1 gives
The sum is:  595
Method 2 gives
The sum is:  595
Method 3 gives
The sum is:  595

```

```Example 19
# powers of 2 using anonymous function
terms = 0
while True:
try:
terms = int(raw_input("How many terms? "))
if terms < 1:
print "Somethng went wrong"
continue
break
except:
print "Something went wrong"
continue

# anonymous function
result = list(map(lambda x: 2 ** x, range(terms)))

for i in range(terms):
print "2 ^ ",i ," = ", result[i]

@IDLE
How many terms? 10
2 ^  0  =  1
2 ^  1  =  2
2 ^  2  =  4
2 ^  3  =  8
2 ^  4  =  16
2 ^  5  =  32
2 ^  6  =  64
2 ^  7  =  128
2 ^  8  =  256
2 ^  9  =  512

```

```Example 20
# List and Lambda
theList = 
for i in range (2,250):
theList.append(i)

result = list(filter(lambda x: (x % 13 == 0), theList))

# display the result
print "Numbers divisible by 13 are:\n", result

@IDLE
Numbers divisible by 13 are:
[13, 26, 39, 52, 65, 78, 91, 104, 117, 130, 143, 156, 169, 182, 195, 208, 221, 234, 247]

```

```Example 21
# convert decimal to binary, octal and hexadecimal
def convert(fromNum,fromBase, toBase):
toNum = 0
power = 0
while fromNum > 0:
toNum += fromBase ** power * (fromNum % toBase)
fromNum //=  toBase
power += 1

print "Binary, Octal and Hexadecimal representation of decimal upto 20\n {:3s} {:10s} {:10s} {:10s}".format("dec","bin","oct","hex")
for i in range(0,21):
print '{:3d} {:10s} {:10s}  {:10s}'.format(i,bin(i),oct(i),hex(i))

print "\nBinary, Octal and Hexadecimal representation of decimal upto 20\n {:3s} {:10s} {:10s} {:10s}".format("dec","bin","oct","hex")
for i in range(0,21):
print '{:3d} {:10d} {:10d} {:10d}'.format(i,convert(i,10,2),convert(i,10,8),convert(i,10,16))

@IDLE
Binary, Octal and Hexadecimal representation of decimal upto 20
dec bin        oct        hex
0 0b0        0           0x0
1 0b1        01          0x1
2 0b10       02          0x2
3 0b11       03          0x3
4 0b100      04          0x4
5 0b101      05          0x5
6 0b110      06          0x6
7 0b111      07          0x7
8 0b1000     010         0x8
9 0b1001     011         0x9
10 0b1010     012         0xa
11 0b1011     013         0xb
12 0b1100     014         0xc
13 0b1101     015         0xd
14 0b1110     016         0xe
15 0b1111     017         0xf
16 0b10000    020         0x10
17 0b10001    021         0x11
18 0b10010    022         0x12
19 0b10011    023         0x13
20 0b10100    024         0x14

Binary, Octal and Hexadecimal representation of decimal upto 20
dec bin        oct        hex
0          0          0          0
1          1          1          1
2         10          2          2
3         11          3          3
4        100          4          4
5        101          5          5
6        110          6          6
7        111          7          7
8       1000         10          8
9       1001         11          9
10       1010         12         10
11       1011         13         11
12       1100         14         12
13       1101         15         13
14       1110         16         14
15       1111         17         15
16      10000         20         10
17      10001         21         11
18      10010         22         12
19      10011         23         13
20      10100         24         14

```

```Example 22
# python characters and ascii values
import string
print "Total ", len(string.printable), "\n", string.printable

for i in range(0,128):
print chr(i), " ", ord(chr(i))

@IDLE
Total  100
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#\$%&'()*+,-./:;<=>?@[\]^_`{|}~

```

```Example 23
# Find the G.C.D. & L.C.M. of two

# gcd function
def gcd(x, y):
while(y):
x, y = y, x % y
return x

# lcm function
def lcm(x, y):
lcm = (x*y)//gcd(x,y)
return lcm

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

print "The L.C.M. of ", num1," and ", num2," is ", lcm(num1, num2)
print "The G.C.D. of ", num1," and ", num2," is ", gcd(num1, num2)

@IDLE
Enter first number: 54
Enter second number: 24
The L.C.M. of  54  and  24  is  216
The G.C.D. of  54  and  24  is  6

```

```Example 24
# factors of a number
def factors(x):
print "The factors of ", x, " are:"
for i in range(1, x + 1):
if x % i == 0:
print(i),
num = 0
while True:
try:
num = int(raw_input("Enter a number: "))
if num < 1:
print "Not taking negative numbers"
continue
break
except:
print "Something went wrong"
continue
factors(num)

@IDLE
Enter a number: 999
The factors of  999  are:
1 3 9 27 37 111 333 999

```

```Example 25
# simple calculator
return x + y

def subtract(x, y):
return x - y

def multiply(x, y):
return x * y

def divide(x, y):
x = float(x)
y = float(y)
return x / y

num1 = 0
while True:
try:
num1 = int(raw_input("Enter first number: "))
break
except:
print "Something went wrong"
continue
num2 = 0
while True:
try:
num2 = int(raw_input("Enter second number: "))
break
except:
print "Something went wrong"
continue

choice = 0
while True:
try:
print("\nSelect operation.")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = int(raw_input("Enter choice(1/2/3/4 - 0 to quit):"))
if choice == 1:
elif choice == 2:
print num1,"-",num2,"=", subtract(num1,num2)
elif choice == 3:
print num1,"*",num2,"=", multiply(num1,num2)
elif choice == 4:
print num1,"/",num2,"=", divide(num1,num2)
elif choice == 0:
break
else:
print "Invalid input"
continue
except:
print "Something went wrong"
continue

@IDLE
Enter first number: 12
Enter second number: 23

Select operation.
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4 - 0 to quit):1
12 + 23 = 35

Select operation.
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4 - 0 to quit):2
12 - 23 = -11

Select operation.
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4 - 0 to quit):3
12 * 23 = 276

Select operation.
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4 - 0 to quit):4
12 / 23 = 0.521739130435

Select operation.
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4 - 0 to quit):0
>>>

```

```Example 26
# shuffle a deck of card and draw 5 cards
import itertools, random

# make a deck of cards

quitLoop = ""
while True:
# shuffle the cards
random.shuffle(deck)

# draw five cards
print
for i in range(5):
print deck[i], "of", deck[i]

quitLoop = raw_input("press enter to reshuffle (enter q to quit)\n")
if quitLoop.lower() == "q":
break

@IDLE
5 of Diamond
8 of Club
12 of Heart
13 of Diamond
1 of Heart
press enter to reshuffle (enter q to quit)

8 of Heart
4 of Club
9 of Diamond
press enter to reshuffle (enter q to quit)

12 of Heart
5 of Heart
13 of Heart
2 of Club
11 of Heart
press enter to reshuffle (enter q to quit)

7 of Heart
13 of Heart
12 of Heart
1 of Club
press enter to reshuffle (enter q to quit)
q

```

```Example 27
# calendar of current year
import calendar
import datetime
from datetime import date
from time import gmtime, strftime

currentYear = date.today().year
currentMonth = date.today().month

print(calendar.month(currentYear,currentMonth))
print "It's ", strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

@IDLE
May 2016
Mo Tu We Th Fr Sa Su
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

It's  Sun, 01 May 2016 11:00:14 +0000

```

```Example 28
for i in range(len(X)):
for j in range(len(X)):
result[i][j] = X[i][j] + Y[i][j]
return result

X = [[12, 7, 3],
[44 ,5, 6],
[73 ,8, 9]]

Y = [[5, 8, 1],
[6, 7, 3],
[4, 5, 9]]

result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]

print "First matrix"
for each in X:
print (each)

print "Second matrix"
for each in Y:
print (each)

print "\nOn addition first method gives"
for r in result1:
print (r)

print "\nOn addition second method gives"
result2 = [[X[i][j] + Y[i][j]  for j in range(len(X))] for i in range(len(X))]
for r in result2:
print (r)

@IDLE
First matrix
[12, 7, 3]
[44, 5, 6]
[73, 8, 9]
Second matrix
[5, 8, 1]
[6, 7, 3]
[4, 5, 9]

[17, 15, 4]
[50, 12, 9]
[77, 13, 18]

[17, 15, 4]
[50, 12, 9]
[77, 13, 18]

```

```Example 29
# matrix
for i in range(len(X)):
for j in range(len(X)):
result[i][j] = X[i][j] + Y[i][j]
return result

def transpose(matrix):
return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]

def multiply1(X,Y):
result = [[0,0,0], [0,0,0], [0,0,0]]
for i in range(len(X)):
for j in range(len(Y)):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
return result

X = [[12, 7, 3],
[4 ,5, 6],
[7 ,8, 9]]

Y = [[5, 8, 1],
[6, 7, 3],
[4, 5, 9]]

result = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]

print "First matrix"
for each in X:
print (each)

print "Second matrix"
for each in Y:
print (each)

print "\nOn addition first method gives"
for r in result1:
print (r)

print "\nOn addition second method gives"
result2 = [[X[i][j] + Y[i][j]  for j in range(len(X))] for i in range(len(X))]
for r in result2:
print (r)

T = [[1, 2],
[3 ,4],
[5 ,6]]
print "\nT matrix"
for each in T:
print (each)
print "\nTranspose of T by method 1 is"
result3 = transpose(T)
for r in result3:
print (r)

print "Transpose of T by method 2 is"
result4 = [[T[j][i] for j in range(len(T))] for i in range(len(T))]
for r in result3:
print (r)

print "\nMultiplication of X and Y by method1 gives:"
result5 = multiply1(X,Y)
for r in result5:
print (r)

print "\nMultiplication of X and Y by method2 gives:"
result6 = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]
for r in result6:
print (r)

@IDLE
First matrix
[12, 7, 3]
[4, 5, 6]
[7, 8, 9]
Second matrix
[5, 8, 1]
[6, 7, 3]
[4, 5, 9]

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

T matrix
[1, 2]
[3, 4]
[5, 6]

Transpose of T by method 1 is
[1, 3, 5]
[2, 4, 6]
Transpose of T by method 2 is
[1, 3, 5]
[2, 4, 6]

Multiplication of X and Y by method1 gives:
[114, 160, 60]
[74, 97, 73]
[119, 157, 112]

Multiplication of X and Y by method2 gives:
[114, 160, 60]
[74, 97, 73]
[119, 157, 112]

```

```Example 30
# palindrome
my_str = ""
while True:
try:
my_str = raw_input("Enter a string: ")
break
except:
print "Something went wrong"
continue

my_str = my_str.lower()

# reverse the string
rev_str = reversed(my_str)

# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")

listOfPalindromes = {"AMANAPLANACANALPANAMA": "probably the most oft' quoted palindrome of all time, but a phrase nonetheless",
"MALAYALAM": "the Dravidian language of Kerala, and hence a proper noun",
"RACECAR": "a neat word, but strictly a hyphenated form",
"ALULA": "A part of a bird's wing.",
"ANANA": "The pineapple.",
"CIVIC": "Pertaining to cities.",
"DEKED": "From DEKE, to feint in hockey",
"DELED": "From DELE, to delete.",
"DERED": "From DERE, to injure.",
"DEWED": "From DEW, to moisten.",
"KAIAK": "A light canoe.",
"KAYAK": "A light canoe.",
"LEMEL": "Metal filings.",
"LEVEL": "To even out.",
"MALAM": "A Muslim scholar.",
"MINIM": "A musical note.",
"REFER": "To attribute to.",
"ROTOR": "A rotating machine part.",
"SAGAS": "From SAGA, a series of novels.",
"SAMAS": "From SAMA, a Japanese title.",
"SEDES": "A seat (Latin).",
"SELES": "From SELE, good fortune.",
"SEMES": "From SEME, an ornamental pattern.",
"SERES": "From SERE, to burn the surface of.",
"SEXES": "From SEX, gender.",
"SHAHS": "From SHAH, an Iranian ruler.",
"SIMIS": "From SIMI, a type of sword.",
"SIRIS": "From SIRI, a climbing plant.",
"SOLOS": "From SOLO, to perform alone.",
"STATS": "From STAT, a statistic.",
"STETS": "From STET, to cancel a printing correction.",
"STOTS": "From STOT, to bounce.",
"SULUS": "From SULU, a Melanesian skirt.",
"SUSUS": "From SUSU, a group savings scheme.",
"TENET": "A principle.",
"TOROT": "The body of Jewish law.",
"ARAARA": "A type of fish.",
"ATAATA": "A marine gastropod.",
"DEGGED": "From DEG, to water plants.",
"DENNED": "From DEN, to retire to a lair.",
"HAJJAH": "A Muslim woman who has made a pilgrimage to Mecca.",
"MALLAM": "An African teacher.",
"MARRAM": "A type of grass.",
"PULLUP": "A body-lifting movement.",
"REDDER": "More red.",
"SERRES": "From SERRE, to press close.",
"SESSES": "From SESS, a tax.",
"SUCCUS": "Animal or plant secretion.",
"TALLAT": "A loft.",
"TERRET": "A swivel-ring.",
"TIRRIT": "Fright (Shakesp.)",
"DEIFIED": "From DEIFY, to revere as a god.",
"HALALAH": "A Saudi Arabian monetary unit.",
"REIFIER": "From REIFY, to materialize.",
"REPAPER": "To paper again.",
"REVIVER": "One who revives.",
"ROTATOR": "Something that rotates.",
"SEITIES": "From SEITY, personal identity.",
"SEMEMES": "From SEMEME, a unit of meaning.",
"ROTAVATOR": "A soil-tilling machine." }
print "\nList of palindromes"
for each in listOfPalindromes:
print each, "\t",

@IDLE
Enter a string: 123321
It is palindrome

List of palindromes
DENNED  DELED   ARAARA  RACECAR     TIRRIT  ROTATOR     REIFIER     MALAYALAM   DERED   SAMAS   ROTAVATOR   REDDER  SESSES  DEWED   LEMEL   SUSUS   CIVIC   ALULA   DEIFIED     MINIM   STOTS   SELLES  ANANA   STETS   SERES   ATAATA  PULLUP  MALAM   SEITIES     SUCCUS  SULUS   HAJJAH  ROTOR   STATS   TALLAT  LEVEL   REPAPER     SEMEMES     SIMIS   MALLAM  MARRAM  HALLAH  SELES   REVIVER     SEXES   TERRET  SOLOS   TOROT   SEMES   DEKED   REFER   KAIAK   MADAM   SEDES   AMANAPLANACANALPANAMA   SHAHS   TENET   KAYAK   RADAR   SAGAS   HADEDAH     DEGGED  SERRES  SIRIS   HALALAH

```

```Example 31
# remove punctuations
punctuations = '''!()-[]{};:'"\,<>./?@#\$%^&*_~'''

my_str = '\'a\'n! (A)s-h[i]s{h} ;R:a\'n"j\\a,n< >p.r/e?s@e#n\$t%a^t&i*o_n~'''

no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char

print(no_punct)

@IDLE
an Ashish Ranjan presentation

```

```Example 32
# sort alphabetically the words form a string
my_str = "The quick brown fox jumps over the lazy dog"

# breakdown the string into a list of words
words = my_str.split()

# sort the list
words.sort()

# display the sorted words
for word in words:
print(word)

@IDLE
The
brown
dog
fox
jumps
lazy
over
quick
the

```

```Example 33
# set operations
E = {0, 2, 4, 6, 8};
N = {1, 2, 3, 4, 5};

print "Set 'E' is: ", E
print "Set 'N' is: ", N

print

# set union
print "Union of E and N is: ", E | N

# set intersection
print "Intersection of E and N is: ", E & N

# set difference
print "Difference of E and N is: ", E - N

# set symmetric difference
print "Symmetric difference of E and N is: ", E ^ N

@IDLE
Set 'E' is:  set([8, 0, 2, 4, 6])
Set 'N' is:  set([1, 2, 3, 4, 5])

Union of E and N is:  set([0, 1, 2, 3, 4, 5, 6, 8])
Intersection of E and N is:  set([2, 4])
Difference of E and N is:  set([8, 0, 6])
Symmetric difference of E and N is:  set([0, 1, 3, 5, 6, 8])

```

```Example 34
# count the number of each vowel in a string

# string of vowels
vowels = 'aeiou'

ip_str = "an Ashish Ranjan presentation"

# make it suitable for caseless comparisions
ip_str = ip_str.lower()

# make a dictionary with each vowel a key and value 0
count = {}.fromkeys(vowels,0)

# count the vowels
for char in ip_str:
if char in count:
count[char] += 1

print(count)

@IDLE
{'a': 5, 'i': 2, 'e': 2, 'u': 0, 'o': 1}

```

```Example 35
# Pyfind the SHA-1 message digest of a file

import hashlib

def hash_file(filename):
# make a hash object
h = hashlib.sha1()

# open file for reading in binary mode
with open(filename,'rb') as file:

# loop till the end of the file
chunk = 0
while chunk != b'':
# read only 1024 bytes at a time
h.update(chunk)

# return the hex representation of digest
return h.hexdigest()

message = hash_file("img1.jpg")
print(message)

@IDLE
4733fa9d89229df2976706d74df90c0e998476a2

```

```Example 36
# get image info
import struct

def get_image_info(data):
if is_png(data):
w, h = struct.unpack('>LL', data[16:24])
width = int(w)
height = int(h)
else:
raise Exception('not a png image')
return width, height

def is_png(data):
return (data[:8] == '\211PNG\r\n\032\n'and (data[12:16] == 'IHDR'))

if __name__ == '__main__':
with open('img1.jpg', 'rb') as f: