Chapter 10: Miscellany

Example 10.1, Page number: 356

In [ ]:
import sys

# Calculation and result
i = 0
for arg in sys.argv :
   print ('arg [%d] - %s' % (i, arg))
   i = i+1
In [5]:
%run 10.1.py hello world
arg [0] - 10.1.py
arg [1] - hello
arg [2] - world

Example 10.2, Page number: 358

In [ ]:
import sys

# Function declaration, calculation and result
if len(sys.argv) != 2 :
	print ('Inappropriate number of arguments')
	
total = 0
def fact (n) :
   total = n
   while n > 1 :
      total = total * (n - 1)
      n = n - 1
   return total

print ('Factorial of %d is %d ' % (int(sys.argv[1]), fact (int(sys.argv[1]))))
In [7]:
%run 10.2.py 5
Factorial of 5 is 120 

Example 10.3, Page number: 361

In [ ]:
import sys

# Function declaration
def printdata () :
	i = 0
	for arg in sys.argv[1:] :
		print ('The data in cell [%d] is %s ' % (i, arg))
		i = i+1

# Calculation and result
print ('The names before sorting are ')
printdata ()

sys.argv.sort()   

print ('The names after sorting are ')
printdata ()
In [8]:
%run 10.3.py zimbabwe nigeria argentina china hongkong
The names before sorting are 
The data in cell [0] is zimbabwe 
The data in cell [1] is nigeria 
The data in cell [2] is argentina 
The data in cell [3] is china 
The data in cell [4] is hongkong 
The names after sorting are 
The data in cell [0] is argentina 
The data in cell [1] is china 
The data in cell [2] is hongkong 
The data in cell [3] is nigeria 
The data in cell [4] is zimbabwe 

Example 10.4, Page number: 377

In [13]:
# Variable declaration
a = int(raw_input('Enter any positive number '))

# Function declaration, calculation and result
def convert (a) :
    return int(bin(a)[2:])

bits = str(convert (a))
print ('Number of bits = %d' % (len(bits)))
print ('Binary equivalent is : %d' % (convert (a)))
Enter any positive number 16
Number of bits = 5
Binary equivalent is : 10000

Example 10.5, Page number: 379

In [11]:
# Variable declaration
a = int(raw_input('Enter first number : '))
b = int(raw_input('Enter second number : '))

# Calculation and result
b = ~b + 1
c = a + b

print ('Subtraction is = %d ' % c)
Enter first number : 7
Enter second number : 3
Subtraction is = 4 

Example 10.6, Page number: 380

In [12]:
# Variable declaration
a = int(raw_input('Enter first number : '))
original_a = a

b = int(raw_input('Enter second number : '))
original_b = b

# Calculation and result
c = 1
while (b) :
	if (b & 1) :
		c = c * a
	b = b >> 1
	a = a * a

print ('%d raise to %d = %d ' % (original_a, original_b, c))
Enter first number : 7
Enter second number : 3
7 raise to 3 = 343