# Chapter 6: Loop Control Statements

### Example 6.1, Page number: 107

In [1]:
#Print the first five numbers starting from one together with thier squares

#Result
#Since range() function starts with 0; to print upto 5, use 5+1 or 6
#range() function creates range or numbers from 1 to 6

for i in range(1,5+1):
print("Number : %d   it's Square : %d"%(i,i*i))

Number : 1   it's Square : 1
Number : 2   it's Square : 4
Number : 3   it's Square : 9
Number : 4   it's Square : 16
Number : 5   it's Square : 25


### Example 6.2, Page number: 108

In [2]:
#Display numbers from 1 to 15 using for loop.  Use i++

import sys

#Result
#There is no increment operator (++) in python
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for i in range(1,15+1):
sys.stdout.write("%5d"%(i))

    1    2    3    4    5    6    7    8    9   10   11   12   13   14   15

### Example 6.3, Page number: 108

In [3]:
#Display numbers from 1 to 15 using for loop. Use i = i + 1

import sys

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for i in range(1,15+1):
sys.stdout.write("%5d"%(i))

    1    2    3    4    5    6    7    8    9   10   11   12   13   14   15

### Example 6.4, Page number: 109

In [4]:
#Display numbers from 1 to 16. Use incrementation operation in the body of
#the loop for more than once

import sys

#Variable declaration

c = 0

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers and the third argument in the range function
#indicates the interval between the numbers.

for i in range(0,15+1,2):
i += 1
sys.stdout.write("%5d"%(i))
i = i + 1
sys.stdout.write("%5d"%(i))
c += 1

sys.stdout.write("\n\nThe Body of the loop is executed for %d times"%(c))

    1    2    3    4    5    6    7    8    9   10   11   12   13   14   15   16

The Body of the loop is executed for 8 times

### Example 6.5, Page number: 109

In [5]:
#Display even numbers from 0 to 14 by declaring the initial counter value before
#the loop statement
import sys

#Variable declaration

c = 0
i = 0

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers and the third argument in the range function
#indicates the interval between the numbers.

#counter variable initialization before the for loop will not affect much.

for i in range(0,15+1,2):
sys.stdout.write("%5d"%(i))


    0    2    4    6    8   10   12   14

### Example 6.6, Page number: 110

In [6]:
#Display numbers in ascending and descending orders.

import sys

#Variable declaration

i = 0

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers and the third argument in the range function
#indicates the interval between the numbers.

#counter variable initialization before the for loop will not affect much.

sys.stdout.write("Numbers in Ascending Order : ")
for i in range(1,10+1):
sys.stdout.write("%3d"%(i))

sys.stdout.write("\nNumbers in Descending Order : ")
for i in range(10,0,-1):
sys.stdout.write("%3d"%(i))

Numbers in Ascending Order :   1  2  3  4  5  6  7  8  9 10
Numbers in Descending Order :  10  9  8  7  6  5  4  3  2  1

### Example 6.7, Page number: 110

In [7]:
#Display numbers upto 10 using infinite for loop.  Use goto statement to
#exit from the loop

import sys

#Variable declaration

i = 0

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers and the third argument in the range function
#indicates the interval between the numbers.

#counter variable initialization before the for loop will not affect much.

for i in range(0,15):
sys.stdout.write("%3d"%(i))
i += 1
if i == 11:
break

#there is no infinite for loop and goto statement in python.

  0  1  2  3  4  5  6  7  8  9 10

### Example 6.8, Page number: 111

In [8]:
#Count numbers between 1 to 100 not divisible by 2, 3, and 5

import sys

#Variable declaration

c = 0

sys.stdout.write("\nNumbers from 1 to 100 not divisible by 2,3&5\n\n")

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for x in range(0,100+1):
if x%2 != 0 and x%3 != 0 and x%5 != 0:
sys.stdout.write("%d\t"%(x))
c += 1

sys.stdout.write("\nTotal Numbers : %d"%(c))

Numbers from 1 to 100 not divisible by 2,3&5

1	7	11	13	17	19	23	29	31	37	41	43	47	49	53	59	61	67	71	73	77	79	83	89	91	97
Total Numbers : 26

### Example 6.9, Page number: 112

In [1]:
#Display the numbers in increasing and decreasing order using infinite
#for loop

import sys

#Variable declaration
n = int(raw_input("Enter a number : "))
a = b = n

sys.stdout.write("(++)        (--)\n")
sys.stdout.write("===================")

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

#There is no infinite for loop in python. so separate iteration variable i is used

for i in range(0,100):
sys.stdout.write("\n%d\t%d"%(a,b))
if b == 0:
break
a += 1
b -= 1

Enter a number : 5
(++)        (--)
===================
5	5
6	4
7	3
8	2
9	1
10	0

### Example 6.10, Page number: 113

In [1]:
#Create an infinite loop. Check each value of the for loop.  if the value is
#even, display it otherwise continue with interations.  Print even numbers from
#1 to 21. Use break statement to terminate the program.

import sys

#Variable declaration
i = 1

sys.stdout.write("\n\t\tTable of Even numbers from 1 to 20")
sys.stdout.write("\n\t\t==================================\n")

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

#There is no infinite for loop in python. so separate iteration variable i is used

for i in range(1,100):
if i == 20:
break
else:
if i%2 == 0:
sys.stdout.write("%d\t"%(i))
continue
else:
continue

		Table of Even numbers from 1 to 20
==================================
2	4	6	8	10	12	14	16	18	

### Example 6.11, Page number: 113

In [14]:
#Calculate the sum of first five numbers and their squares.  Display their results

import sys

#Variable declaration
#since sum is a function in python, sum1 is used instead of variable sum.

sum1 = 0
sqsum = 0

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for i in range(1,5+1):
sum1 += i
sqsum += i*i
sys.stdout.write("\nNumber : %5d    it's Square : %8d"%(i,i*i))

sys.stdout.write("\n=================================================")
sys.stdout.write("\nThe Sum %6d Sum of Squares %9d"%(sum1,sqsum))

Number :     1    it's Square :        1
Number :     2    it's Square :        4
Number :     3    it's Square :        9
Number :     4    it's Square :       16
Number :     5    it's Square :       25
=================================================
The Sum     15 Sum of Squares        55

### Example 6.12, Page number: 114

In [15]:
#Display numbers from 1 to 9 and their square roots.

import math
import sys

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for i in range(1,9+1):
a = math.sqrt(i)
sys.stdout.write("\n\t%d     %.2f"%(i,a))

	1     1.00
2     1.41
3     1.73
4     2.00
5     2.24
6     2.45
7     2.65
8     2.83
9     3.00

### Example 6.13, Page number: 115

In [16]:
#Find the number in between 7 and 100 which is exactly divisible by
#4 and if divided by 5 and 6 remainders obtained should be 4.

import sys

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for x in range(7,100+1):
if x%4 == 0 and x%5 == 4 and x%6 == 4:
sys.stdout.write("\nMinimum Number : %d"%(x))

Minimum Number : 64

### Example 6.14, Page number: 115

In [2]:
#Evaluate the series given
# x = 1/1 + 1/4 + 1/9 ... 1/n2
# y = 1/1 + 1/8 + 1/27 ... 1/n3

#Variable declaration
x = 0.0
y = 0.0
n = int(raw_input("Enter Value of n : "))

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for i in range(1,n+1):
x = x + (1.0/pow(i,2))
y = y + (1.0/pow(i,3))

print("Value of x = %f"%(x))
print("\nValue of y = %f"%(y))

Enter Value of n : 2
Value of x = 1.250000

Value of y = 1.125000


### Example 6.15, Page number: 116

In [3]:
#Generate Triangular number
#Note: Triangular number is nothing but summation of 1 to given number.
#For example, when entered number is 5 it's triangular number would be
#(1+2+3+4+5) = 15.

#Variable declaration
tri_num = 0
n = int(raw_input("What Triangular number do you want : "))

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

for j in range(1,n+1):
tri_num = tri_num + j

print("Triangular number of %d is %d\n"%(n,tri_num))

What Triangular number do you want : 5
Triangular number of 5 is 15



### Example 6.16, Page number: 117

In [4]:
#Find sum of the following series
# 1 + 2 + 3 + ... n
# 1^2 + 2^2 + 2^3 + ... n^2

import sys

#Variable declaration
#since sum is a function name in python, sum1 is used instead of sum.

sum1 = 0
ssum = 0
j = int(raw_input("Enter Number : "))

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

sys.stdout.write("Numbers : ")
for i in range(1,j+1):
sys.stdout.write("%5d"%(i))

sys.stdout.write("\nSquares : ")
for i in range(1,j+1):
sys.stdout.write("%5d"%(i*i))
sum1 = sum1 + i
ssum = ssum + i*i
sys.stdout.write("\nSum of Numbers from 1 to %d   : %d"%(j,sum1))
sys.stdout.write("\nSum of Squares of 1 to %d Numbers : %d"%(j,ssum))

Enter Number : 5
Numbers :     1    2    3    4    5
Squares :     1    4    9   16   25
Sum of Numbers from 1 to 5   : 15
Sum of Squares of 1 to 5 Numbers : 55

### Example 6.17, Page number: 118

In [20]:
#Display the perfect squares from 1 to 500.

import sys
import math

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers

sys.stdout.write("\n\n")
sys.stdout.write("Perfect square from 1 to 500 \n")
count = 0

for i in range(1,500+1):
c = math.sqrt(i)
x = math.floor(c)                  #For rounding up floor() is used
if c == x:
sys.stdout.write("\t%5d"%(i))
count += 1

sys.stdout.write("\n\nTotal Perfect Squares = %d"%(count))


Perfect square from 1 to 500
1	    4	    9	   16	   25	   36	   49	   64	   81	  100	  121	  144	  169	  196	  225	  256	  289	  324	  361	  400	  441	  484

Total Perfect Squares = 22

### Example 6.18, Page number: 119

In [5]:
#Detect the largest number out of five numbers.

import sys
import math

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers.
#since sum is a built in function in python, sum1 is used instead of sum.

a = int(raw_input("Enter five numbers : "))
b = int(raw_input("Enter five numbers : "))
c = int(raw_input("Enter five numbers : "))
d = int(raw_input("Enter five numbers : "))
e = int(raw_input("Enter five numbers : "))

sum1 = a + b + c + d + e

for i in range(sum1,1,-1):
if i == a or i == b or i == c or i == d or i == e:
sys.stdout.write("The Largest Number : %d"%(i))
break

Enter five numbers : 5
Enter five numbers : 2
Enter five numbers : 3
Enter five numbers : 7
Enter five numbers : 3
The Largest Number : 7

### Example 6.19, Page number: 119

In [6]:
#Detect the smallesst number out of five numbers.

import sys
import math

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers.
#since sum is a built in function in python, sum1 is used instead of sum.

a = int(raw_input("Enter five numbers : "))
b = int(raw_input("Enter five numbers : "))
c = int(raw_input("Enter five numbers : "))
d = int(raw_input("Enter five numbers : "))
e = int(raw_input("Enter five numbers : "))

sum1 = a + b + c + d + e

for i in range(1,sum1):
if i == a or i == b or i == c or i == d or i == e:
sys.stdout.write("The Smallest Number : %d"%(i))
break

Enter five numbers : 5
Enter five numbers : 2
Enter five numbers : 3
Enter five numbers : 7
Enter five numbers : 3
The Smallest Number : 2

### Example 6.20, Page number: 120

In [7]:
#Read five numbers and print in ascending order

import sys
import math

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers.
#since sum is a built in function in python, sum1 is used instead of sum.

#use commas to separate the input values
a = int(raw_input("Enter five numbers : "))
b = int(raw_input("Enter five numbers : "))
c = int(raw_input("Enter five numbers : "))
d = int(raw_input("Enter five numbers : "))
e = int(raw_input("Enter five numbers : "))

sys.stdout.write("Numbers in ascending order : ")
sum1 = a + b + c + d + e

for i in range(1,sum1):
if i == a or i == b or i == c or i == d or i == e:
sys.stdout.write("%3d"%(i))

Enter five numbers : 5
Enter five numbers : 8
Enter five numbers : 7
Enter five numbers : 4
Enter five numbers : 1
Numbers in ascending order :   1  4  5  7  8

### Example 6.21, Page number: 121

In [8]:
#Perform multiplication of two integers by using negative sign

import sys

#Result
#the range() function creates range of numbers and for loop automatically
#iterate through the numbers.

a = int(raw_input("Enter two numbers : "))
b = int(raw_input("Enter two numbers : "))

d = 0
for c in range(1,b+1):
d = d - (-a)

sys.stdout.write("Multiplication of %d * %d : %d"%(a,b,d))

Enter two numbers : 5
Enter two numbers : 5
Multiplication of 5 * 5 : 25

### Example 6.22, Page number: 121

In [9]:
#Perform multiplication of two integers by using repetitive addition

import sys

#Result
#in python, infinite for loop is not possible.

a = int(raw_input("Enter two numbers : "))
b = int(raw_input("Enter two numbers : "))

d = 0
c = 1
while True:
d = d + a
if c == b:
break
c += 1

sys.stdout.write("Multiplication of %d * %d : %d"%(a,b,d))

Enter two numbers : 8
Enter two numbers : 4
Multiplication of 8 * 4 : 32

### Example 6.23, Page number: 122

In [*]:
#Read the marks for five subjects and calculate sum & average of marks.

import sys

#Result
#use spaces to separate the input values
#since sum is a built-in function in python, sum1 is used as the variable name

sys.stdout.write("Enter The Marks of Five Subjects ")
sum1 = 0

for i in range(1,5+1):
sys.stdout.write("[%d] Student  : "%(i))
#Exception handling
try:
#use space to separate the input characters
v = raw_input("")
a,b,c,d,e = map(int,v.split())
x = 5
except:
x = 0

if(x == 5):
sum1 = a + b + c + d + e
avg = sum1/5
sys.stdout.write("\nTotal Marks of Student [%d] %d"%(i,sum1))
sys.stdout.write("\nAverage Marks of Student [%d] %f"%(i,avg))
else:
sys.stdout.write("Type Mismatch")

Enter The Marks of Five Subjects [1] Student  : 58 52 52 56 78

Total Marks of Student [1] 296
Average Marks of Student [1] 59.000000[2] Student  : 

### Example 6.24, Page number: 123

In [2]:
#Enter a character and display its position in alphabetic order.

import sys

#Variable Initialization
c = 1

ch = raw_input("Enter a character :")
ch = ch.upper()

#Result

#ord() function converts the character ASCII value to integer
for i in range(65,90+1):
if ord(ch) == i:
sys.stdout.write("'%c' is %d [st/nd/rd/th] Character in Alphabetic"%(i,c))
c += 1

Enter a character :U
'U' is 21 [st/nd/rd/th] Character in Alphabetic

### Example 6.25, Page number: 124

In [2]:
#Calculate the value of -m^x.
#'m' is a mantissa and 'x' is an exponent

import sys

#Variable Initialization
number = int(raw_input("Enter Number : "))
power = int(raw_input("Enter Power : "))

ans = 1

#Calculation
for i in range(1,power+1):
ans *= number

#Result
sys.stdout.write("The Power of %d raised to %d is %ld"%(number,power,ans))

Enter Number : 5
Enter Power : 3
The Power of 5 raised to 3 is 125

### Example 6.26, Page number: 124

In [31]:
#Subtraction of two loop variables using nested for loops.

import sys

#Calculation & Result
for a in range(3,0,-1):
for b in range(1,2+1):
sub = a - b
sys.stdout.write("a = %d  b = %d  a - b = %d\n"%(a,b,sub))

a = 3  b = 1  a - b = 2
a = 3  b = 2  a - b = 1
a = 2  b = 1  a - b = 1
a = 2  b = 2  a - b = 0
a = 1  b = 1  a - b = 0
a = 1  b = 2  a - b = -1


### Example 6.27, Page number: 125

In [32]:
#Illustrate an example based on nested for loops

import sys

#Calculation & Result
for i in range(1,3+1):                  #outer loop
for j in range(1,2+1):              #inner loop
sys.stdout.write("\ni * j : %d"%(i*j))

i * j : 1
i * j : 2
i * j : 2
i * j : 4
i * j : 3
i * j : 6

### Example 6.28, Page number: 126

In [33]:
#Print values and messages when any loop ends using nested for loops.

import sys

#Calculation & Result
for a in range(1,2+1):                  #outer loop
for b in range(1,2+1):              #middle loop
for c in range(1,2+1):          #inner loop
sys.stdout.write("\na = %d + b = %d + c = %d : %d"%(a,b,c,a+b+c))
sys.stdout.write("\nInner Loop Over.")
sys.stdout.write("\nMiddle Loop Over.")
sys.stdout.write("\nOuter Loop Over.")

a = 1 + b = 1 + c = 1 : 3
a = 1 + b = 1 + c = 2 : 4
Inner Loop Over.
a = 1 + b = 2 + c = 1 : 4
a = 1 + b = 2 + c = 2 : 5
Inner Loop Over.
Middle Loop Over.
a = 2 + b = 1 + c = 1 : 4
a = 2 + b = 1 + c = 2 : 5
Inner Loop Over.
a = 2 + b = 2 + c = 1 : 5
a = 2 + b = 2 + c = 2 : 6
Inner Loop Over.
Middle Loop Over.
Outer Loop Over.

### Example 6.29, Page number: 127

In [3]:
#Display perfect cubes up to given number.

import sys

#Variable Initialization
k = int(raw_input("Enter a Number : "))

#Calculation & Result
for i in range(1,k+1):
for j in range(1,i+1):
if i == pow(j,3):
sys.stdout.write("\nNumber : %d & it's Cube : %d"%(j,i))


Enter a Number : 100

Number : 1 & it's Cube : 1
Number : 2 & it's Cube : 8
Number : 3 & it's Cube : 27
Number : 4 & it's Cube : 64

### Example 6.30, Page number: 128

In [16]:
#Display numbers 1 to 100 using ASCII values from 48 to 57. Use nested loops.

import sys

#Variable Initialization
j = 0
k = -9

sys.stdout.write("\tTable of 1 to 100 Numbers Using ASCII Values\n")
sys.stdout.write("\t===== == = == === ======= ===== ===== ======\n")

#Calculation & Result
for i in range(48,57+1):
for j in range(48,57+1):
sys.stdout.write("\t%c%c"%(i,j))
#if k != 1:
#   sys.stdout.write("%c"%(i+1))
#if k == 0:
#   sys.stdout.write("\b\b%d"%(k+1))
sys.stdout.write("\n")
k += 1


	Table of 1 to 100 Numbers Using ASCII Values
===== == = == === ======= ===== ===== ======
00	01	02	03	04	05	06	07	08	09
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	76	77	78	79
80	81	82	83	84	85	86	87	88	89
90	91	92	93	94	95	96	97	98	99


### Example 6.31, Page number: 129

In [18]:
#Count number of votes secured by 'A' & 'B'.  Assume three voters are
#voting them. Also count the invalid votes.

import sys

#Variable Initialization & Calculation
a = 0
b = 0
o = 0
sys.stdout.write("Press A or B\n")
for i in range(1,3+1):
sys.stdout.write("\nVoter no. %d"%(i))
sys.stdout.write("  Enter Vote : ")
v = raw_input("")
v = v.upper()
if v == 'A':
a += 1
else:
if v == 'B':
b += 1
else:
o += 1

#Result
sys.stdout.write("\nStatus of vote(s)\n")
sys.stdout.write("\nA secures %d vote(s)."%(a))
sys.stdout.write("\nB secures %d vote(s)."%(b))
sys.stdout.write("\nInvalid vote(s) %d."%(o))

Press A or B

Voter no. 1  Enter Vote : A

Voter no. 2  Enter Vote : B

Voter no. 3  Enter Vote : X

Status of vote(s)

A secures 1 vote(s).
B secures 1 vote(s).
Invalid vote(s) 1.

### Example 6.32, Page number: 130

In [19]:
#Simulate a digital clock

import sys
import os

#Result
sys.stdout.write("hh mm ss\n")
for h in range(1,12):
for m in range(1,59):
for s in range(1,59):
sys.stdout.write("\r%d  %d  %d"%(h,m,s))

#Displays the last value

hh mm ss
11  58  58

### Example 6.33, Page number: 131

In [20]:
#Count occurrence of 0 to 9 digits between 1 and given decimal number

import sys

#Variable Initialization
n = int(raw_input("Enter a Decimal Number : "))
st = [0 for x in range(10)]         #10 array elements initialized as 0

#Calculation
for l in range(1,n+1):
t = l
while t != 0:
k = t % 10
t = t / 10
st[k] += 1

#Result
sys.stdout.write("\nOccurrence of 0-9 digits between 1 to %d Numbers."%(n))
sys.stdout.write("\n========== == === ====== ======= = == == ========")

for i in range(0,10):
if st[i] > 0:
sys.stdout.write("\n%d Occurs %8d Times."%(i,st[i]))

Enter a Decimal Number : 15

Occurrence of 0-9 digits between 1 to 15 Numbers.
========== == === ====== ======= = == == ========
0 Occurs        1 Times.
1 Occurs        8 Times.
2 Occurs        2 Times.
3 Occurs        2 Times.
4 Occurs        2 Times.
5 Occurs        2 Times.
6 Occurs        1 Times.
7 Occurs        1 Times.
8 Occurs        1 Times.
9 Occurs        1 Times.

### Example 6.34, Page number: 132

In [21]:
#Display sum of digits of a given number

import sys

#Variable Initialization
s = 0
n = int(raw_input("Enter a Number : "))

#Calculation & Result

sys.stdout.write("\nSum of Digits till a single digit\n %d"%(n))

while n != 0:
s = s + n%10
n = n/10
if n == 0 and s > 9:
sys.stdout.write("\n %2d"%(s))
n = s
s = 0

sys.stdout.write("\n %2d"%(s))

Enter a Number : 4687

Sum of Digits till a single digit
4687
25
7

### Example 6.35, Page number: 133

In [22]:
#Display octal numbers in binary.  Attach a parity bit with "1"
#if number of 1s are even otherwise "0".
#           OR
#Generate odd parity to octal numbers 0 to 7.  Express each number in binary
#and attach the parity bit

import sys

#Variable Initialization
c = 0
j = 12
k = 2

#Calculation & Result

sys.stdout.write("\nBinary Bits                  Parity Bits")
sys.stdout.write("\n=============               ==============\n")

for x in range(0,8):
k += 1
j = 12
y = x
for a in range(0,3):
b = y % 2
#gotoxy
sys.stdout.write("\t%d"%(b))
y = y / 2
if b == 1:
c += 1
if c%2 == 0:
#gotoxy
sys.stdout.write("\t1")
else:
#gotosy
sys.stdout.write("\t0\n")
c = 0

Binary Bits                  Parity Bits
=============               ==============
0	0	0	1	1	0	0	0
0	1	0	0
1	1	0	1	0	0	1	0
1	0	1	1	0	1	1	1	1	1	1	0


### Example 6.36, Page number: 135

In [24]:
#Evaluate the series x - x^3/3! + x^5/5! - .... x^n/n!

import sys

#Variable Initialization
c = 3.0
f = 1.0

#Give x as float value and n as int value

x = float(raw_input("Enter x & n : "))       #use commas to input values
n = int(raw_input("Enter x & n : "))

sum1 = x                #since sum is built-in function in python,
#sum1 is used instead of sum

#Calculation & Result

for i in range(3,n+1,2):
f = 1
if c%2 != 0:
for l in range(1,i+1):
f = f * l
sum1 = sum1 - pow(x,i)/ f
else:
for l in range(1,i+1):
f = f * l
sum1 = sum1 + pow(x,i)/ f
c += 1

sys.stdout.write("\nSum of series Numbers : %f"%(sum1))

Enter x & n : 2
Enter x & n : 5

Sum of series Numbers : 0.933333

### Example 6.37, Page number: 136

In [25]:
#Evaluate the series  x + x^2/2! + x^4/4! + .... x^n/n!

import sys

#Variable Initialization
f = 1.0

#Give x as float value and y as int value

x = float(raw_input("Enter x & y : "))       #use commas to input values
y = int(raw_input("Enter x & y : "))

sum1 = x                #since sum is built-in function in python,
#sum1 is used instead of sum

#Calculation & Result

for i in range(2,y+1,2):
f = 1
for l in range(1,i+1):
f = f * l
sum1 = sum1 + pow(x,i)/ f

sys.stdout.write("\nSum of Series : %f"%(sum1))

Enter x & y : 4
Enter x & y : 4

Sum of Series : 22.666667

### Example 6.38, Page number: 136

In [31]:
#Evaluate the series 1 - 1/1! + 2/2! - 3/3! .... n/n!

import sys

#Variable Initialization
c = 3

n = int(raw_input("Enter value of n : "))

sum1 = 1.0              #since sum is built-in function in python,
#sum1 is used instead of sum

#Calculation

for i in range(1,n+1):
f = 1.0
if c%2 != 0:
for l in range(1,i+1):
f = f * l
k = float(i / f)
sum1 = sum1 - k
else:
for l in range(1,i+1):
f = f * l
sum1 = sum1 + float(i/f)
c += 1

#Result
sys.stdout.write("\nSum of series Numbers : %f"%(sum1))

Enter value of n : 3

Sum of series Numbers : 0.500000

### Example 6.39, Page number: 137

In [1]:
#Display the Armstrong numbers in three digits from 100 to 999.  If sum of cubes of each digits
#of the number is equal to number itself, then the number is called as an Armstrong number.
#(For eg. 153 = 1^3 + 5^3 + 3^3 = 153)

import sys

#Variable Initialization
cube = 0

sys.stdout.write("The Following Numbers are Armstrong numbers.")

#Calculation & Result

for k in range(100,999+1):
cube = 0
x = 1
d = 3
n = k
while x <= d:
i = n % 10
cube = cube + pow(i,3)
n = n / 10
x += 1
if cube == k:
sys.stdout.write("\n\t%d"%(k))

The Following Numbers are Armstrong numbers.
153
370
371
407

### Example 6.40, Page number: 138

In [32]:
#Example 6.40.py
#Program to display the stars as shown below
#*
#**
#***
#****
#*****

import sys

#Variable Initialization

x = int(raw_input("How many lines stars (*) should be printed ? "))

#Result

for i in range(1,x+1):
for j in range(1,i+1):
sys.stdout.write("*")
sys.stdout.write("\n")

How many lines stars (*) should be printed ? 5
*
**
***
****
*****


### Example 6.41, Page number: 139

In [34]:
#Generate the given pattern
#6 5 4 3 2 1 0
#5 4 3 2 1 0
#4 3 2 1 0
#3 2 1 0
#2 1 0
#1 0
#0

import sys

#Variable Initialization
i = int(raw_input("Enter a Number : "))

#Result

while i >= 0:
c = i
sys.stdout.write("\n")
while True:
sys.stdout.write("%3d"%(c))
if c == 0:
break
c -= 1
i -= 1

Enter a Number : 6

6  5  4  3  2  1  0
5  4  3  2  1  0
4  3  2  1  0
3  2  1  0
2  1  0
1  0
0

### Example 6.42, Page number: 140

In [35]:
#Display the series of numbers as given below
#1
#1 2
#1 2 3
#1 2 3 4

#4 3 2 1
#3 2 1
#2 1
#1

import sys

#Variable Initialization
x = int(raw_input("Enter value of x : "))

#Result

for j in range(1,x+1):
for i in range(1,j+1):
sys.stdout.write("%3d"%(i))
sys.stdout.write("\n")

sys.stdout.write("\n")

for j in range(x,0,-1):
for i in range(j,0,-1):
sys.stdout.write("%3d"%(i))
sys.stdout.write("\n")

Enter value of x : 4
1
1  2
1  2  3
1  2  3  4

4  3  2  1
3  2  1
2  1
1


### Example 6.43, Page number: 142

In [36]:
#Program to display the series of numbers as given below
#1
#2 1
#3 2 1
#4 3 2 1

#4 3 2 1
#3 2 1
#2 1
#1

import sys

#Variable Initialization
x = int(raw_input("Enter value of x : "))

#Result

for j in range(1,x+1):
for i in range(j,0,-1):
sys.stdout.write("%3d"%(i))
sys.stdout.write("\n")

sys.stdout.write("\n")

for j in range(x,0,-1):
for i in range(j,0,-1):
sys.stdout.write("%3d"%(i))
sys.stdout.write("\n")

Enter value of x : 4
1
2  1
3  2  1
4  3  2  1

4  3  2  1
3  2  1
2  1
1


### Example 6.44, Page number: 143

In [37]:
#Generate the pyramid structure using numberical

import sys

#Variable Initialization
x = int(raw_input("Enter a number : "))

#Result

for j in range(0,x+1):
for i in range(0-j,j+1):
sys.stdout.write("%3d"%(abs(i)))
sys.stdout.write("\n")


Enter a number : 3
0
1  0  1
2  1  0  1  2
3  2  1  0  1  2  3


### Example 6.45, Page number: 143

In [38]:
#Convert binary to decimal number

import sys

#Variable Initialization
x = [1 for i in range(1,5+1)]              #defines the array x and initializes the elements with 0
y = x[0]

sys.stdout.write("\nValues in different Iterations")
sys.stdout.write("\n====== == ========= ==========\n")

for i in range(0,4):
y = y * 2 + x[i+1]
sys.stdout.write("[%d] %d\t"%(i+1,y))

sys.stdout.write("\nEquivalent of [")

for i in range(0,5):
sys.stdout.write("%d"%(x[i]))

#Result
sys.stdout.write("] in Decimal Number is : ")
sys.stdout.write("%d\t"%(y))

Values in different Iterations
====== == ========= ==========
[1] 3	[2] 7	[3] 15	[4] 31
Equivalent of [11111] in Decimal Number is : 31	

### Example 6.46, Page number: 144

In [55]:
#Program to add a parity bit with four binary bits such that the total
#number of one's should be even

import sys

#Variable Initialization
bit = [0 for i in range(0,5)]              #defines the array bit and initializes the elements with 0
c = 0

sys.stdout.write("\nEnter four bits : ")

for j in range(0,4):
x = int(raw_input(" "))
bit[j] = x
if bit[j] == 1:
c += 1
else:
if bit[j] > 1 or bit[j] < 0:
j -= 1
continue
if c%2 == 0:
bit[j] = 0
else:
bit[j] = 1

#Result
sys.stdout.write("\nMessage bits together with parity bit : ")
for j in range(0,5):
sys.stdout.write("%d"%(bit[j]))

Enter four bits :  1
1
1
1

Message bits together with parity bit : 11110

### Example 6.47, Page number: 145

In [56]:
#Convert binary to decimal number. Enter the binary bits by using for loop

import sys

#Variable Initialization

z = [0 for i in range(0,10)]                #defines the array z and initializes the elements with 0

sys.stdout.write("Enter the number of bits :- ")
b = int(raw_input(""))

sys.stdout.write("\nEnter the binary bits : ")
for i in range(0,b):
z[i] = int(raw_input(""))

a = z[0]

for i in range(0,b-1):
a = a * 2 + z[i+1]
sys.stdout.write("\n%d"%(a))

#Result
sys.stdout.write("\nDecimal Number is : %d "%(a))

Enter the number of bits :- 5

Enter the binary bits : 1
0
0
0
1

2
4
8
17
Decimal Number is : 17 

### Example 6.48, Page number: 147

In [57]:
#Verify the truth table of AND gate. Assume AND gate has two
#input bits A & B and one output bit C.

import sys

#Variable Initialization

a = [0 for i in range(0,4)]                #defines the array a,b & c  and initializes the elements with 0
b = [0 for i in range(0,4)]
c = [0 for i in range(0,4)]

sys.stdout.write("\nEnter Four Bits : ")
for x in range(0,4):
a[x] = int(raw_input(""))

if a[x] > 1 or a[x] < 0:
x -= 1
continue

sys.stdout.write("\nEnter Four Bits : ")
for x in range(0,4):
b[x] = int(raw_input(""))

if b[x] > 1 or b[x] < 0:
x -= 1
continue

#Result
sys.stdout.write("\nA  B  C")
for x in range(0,4):
if a[x] == 1 and b[x] == 1:
c[x] = 1
else:
c[x] = 0
sys.stdout.write("\n%d  %d  %d"%(a[x],b[x],c[x]))

Enter Four Bits : 1
0
1
0

Enter Four Bits : 1
0
0
1

A  B  C
1  1  1
0  0  0
1  0  0
0  1  0

### Example 6.49, Page number: 148

In [58]:
#Verify the truth table of OR gate.

import sys

#Variable Initialization

a = [0 for i in range(0,4)]                #defines the array a,b & c  and initializes the elements with 0
b = [0 for i in range(0,4)]
c = [0 for i in range(0,4)]

sys.stdout.write("\nEnter Four Bits : ")
for x in range(0,4):
a[x] = int(raw_input(""))

if a[x] > 1 or a[x] < 0:
x -= 1
continue

sys.stdout.write("\nEnter Four Bits : ")
for x in range(0,4):
b[x] = int(raw_input(""))

if b[x] > 1 or b[x] < 0:
x -= 1
continue

#Result
sys.stdout.write("\nA  B  C")
for x in range(0,4):
if a[x] == 0 and b[x] == 0:
c[x] = 0
else:
c[x] = 1
sys.stdout.write("\n%d  %d  %d"%(a[x],b[x],c[x]))

Enter Four Bits : 1
1
1
0

Enter Four Bits : 1
0
0
0

A  B  C
1  1  1
1  0  1
1  0  1
0  0  0

### Example 6.50, Page number: 149

In [59]:
#Verify the truth table of EX-OR gate.

import sys

#Variable Initialization

a = [0 for i in range(0,4)]                #defines the array a,b & c  and initializes the elements with 0
b = [0 for i in range(0,4)]
c = [0 for i in range(0,4)]

sys.stdout.write("\nEnter Four Bits : ")
for x in range(0,4):
a[x] = int(raw_input(""))

if a[x] > 1 or a[x] < 0:
x -= 1
continue

sys.stdout.write("\nEnter Four Bits : ")
for x in range(0,4):
b[x] = int(raw_input(""))

if b[x] > 1 or b[x] < 0:
x -= 1
continue

#Result
sys.stdout.write("\nA  B  C")
for x in range(0,4):
if a[x] == 0 and b[x] == 1:
c[x] = 1
else:
if a[x] == 1 and b[x] == 0:
c[x] = 1
else:
c[x] = 0
sys.stdout.write("\n%d  %d  %d"%(a[x],b[x],c[x]))

Enter Four Bits : 1
1
1
0

Enter Four Bits : 1
0
0
0

A  B  C
1  1  0
1  0  1
1  0  1
0  0  0

### Example 6.51, Page number: 151

In [60]:
#Find the Hamming code for the entered binary code.  Assume the binary code of four bits in length.
#The hamming code should be seven bits.

import sys

#Variable Initialization

#defines the array a,b & c  and initializes the elements with 0
b = [0 for i in range(0,4)]
c = [0 for i in range(0,7)]

sys.stdout.write("\nRead the Binary Numbers : ")
for x in range(0,4):
b[x] = int(raw_input(""))

#Piece copy operation
c[0] = b[0]
c[1] = b[1]
c[2] = b[2]
c[4] = b[3]

sys.stdout.write("\nBefore xOR operation : ")

for x in range(0,7):
sys.stdout.write("%3d"%(c[x]))

c[6] = c[0] ^ c[2] ^ c[4]
c[5] = c[0] ^ c[1] ^ c[4]
c[3] = c[0] ^ c[1] ^ c[2]

#Result
sys.stdout.write("\nHamming code after XOR operation : ")
for x in range(0,7):
sys.stdout.write("%3d"%(c[x]))

Read the Binary Numbers : 1
0
1
0

Before xOR operation :   1  0  1  0  0  0  0
Hamming code after XOR operation :   1  0  1  0  0  1  0

### Example 6.52, Page number: 152

In [43]:
#Display the results of students appear in six subjects.  The result declared should be as per the
#following table.
#TOTAL MARKS              RESULT
#>= 420                  Distinction
#>= 360                  First Division
#>= 240                  Second Division
#Otherwise               Fail

import sys

#Variable Initialization
DISTINCTION = 420
FIRST = 360
SECOND = 240

number = int(raw_input("Enter number of Students : "))

for i in range(1,number+1):
roll_no = int(raw_input("Enter Roll Number : "))
total = 0
sys.stdout.write("\nEnter Marks of 6 Subjects for Roll no %d : "%(roll_no))
for j in range(1,6+1):
marks = int(raw_input(""))
total = total + marks
sys.stdout.write("\nTOTAL MARKS = %d"%(total))
if total >= DISTINCTION:
sys.stdout.write("\n(Distinction)\n\n")
else:
if total >= FIRST:
sys.stdout.write("\n(First Division)\n\n")
else:
if total >= SECOND:
sys.stdout.write("\n(Second Division)\n\n")
else:
sys.stdout.write("\n(***Fail***)")


Enter number of Students : 1
Enter Roll Number : 1

Enter Marks of 6 Subjects for Roll no 1 : 42
52
62
72
82
92

TOTAL MARKS = 402
(First Division)



### Example 6.53, Page number: 154

In [26]:
#Print the string "You have learnt C program" 9 times using while loop

#Variable Initialization
x = 1

#Result
while x < 10:
sys.stdout.write("\nYou have learnt C program")
x += 1

You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program
You have learnt C program

### Example 6.54, Page number: 155

In [27]:
#Add 10 consecutive numbers starting from 1 using while loop.

#Variable Initialization
a = 1
sum1 = 0           #since sum is a builtin function in python, sum1 is used instead of sum

#Calculation
while a <= 10:
sys.stdout.write("%3d"%(a))
sum1 = sum1 + a
a += 1

#Result
sys.stdout.write("\nSum of 10 numbers : %d"%(sum1))

  1  2  3  4  5  6  7  8  9 10
Sum of 10 numbers : 55

### Example 6.55, Page number: 155

In [61]:
#Calculate factorial of a given number using while loop.

import sys

#Variable Initialization
fact = 1

a = int(raw_input("Enter The Number : "))

#Calculation
while a >= 1:
sys.stdout.write(" %d * "%(a))
fact = fact * a
a -= 1

#Result
sys.stdout.write(" = %d"%(fact))
sys.stdout.write("\nFactorial of Given number is %d"%(fact))

Enter The Number : 5
5 *  4 *  3 *  2 *  1 *  = 120
Factorial of Given number is 120

### Example 6.56, Page number: 156

In [62]:
#Calculate factorial of a given number using while loop.

import sys

#Variable Initialization
fact = 1
b = 1

a = int(raw_input("Enter The Number : "))

#Calculation
while b <= a:
sys.stdout.write(" %d * "%(b))
fact = fact * b
b += 1

#Result
sys.stdout.write(" = %d"%(fact))
sys.stdout.write("\nFactorial of %d is %d"%(b-1,fact))

Enter The Number : 4
1 *  2 *  3 *  4 *  = 24
Factorial of 4 is 24

### Example 6.57, Page number: 157

In [63]:
#Convert decimal number to binary number

import sys

#Variable Initialization
y = 40
rev = [0 for i in range(1,10)]
c = 1

x = int(raw_input("Enter a Number : "))

#Calculation & Result
#since gotoxy() function is not available in python, the reminders are stored in an array and displayed in reverse order

sys.stdout.write("\nBinary Number : ")
while x != 0:
rev[c] = x % 2
x = x / 2
c += 1

for i in range(c-1,0,-1):
sys.stdout.write("%d"%(rev[i]))

Enter a Number : 25

Binary Number : 11001

### Example 6.58, Page number: 157

In [64]:
#Convert decimal number to user defined number system.

import sys

#Variable Initialization
y = 35
rev = 0
c = 1
rev = [0 for i in range(1,10)]

m = int(raw_input("Enter the Decimal Number : "))
b = int(raw_input("Enter base of number system : "))

#Calculation & Result
sys.stdout.write("\nThe Number Obtained : ")

#since gotoxy() function is not available in python, the reminders are stored in an array and displayed in reverse order
while m != 0:
rev[c] = m % b
c += 1
m = m / b

for i in range(c-1,0,-1):
sys.stdout.write("%d"%rev[i])

Enter the Decimal Number : 50
Enter base of number system : 5

The Number Obtained : 200

### Example 6.59, Page number: 158

In [66]:
#Convert binary number to equivalent decimal number

#Variable Initialization
y = 0
p = 0

n = int(raw_input("Enter a Binary Number : "))

#Calculation
while n != 0:
x = n % 10
if x > 1 or x < 0:
sys.stdout.write("\nInvalid Digit")
break
else:
y = y + x * pow(2,p)
n = n / 10
p += 1

#Result
sys.stdout.write("\nEquivalent Decimal Number is %d."%(y))


Enter a Binary Number : 1111

Equivalent Decimal Number is 15.

### Example 6.60, Page number: 159

In [67]:
#Read a positive integer number 'n' and generate the numbers in the following way.
#If entered number is 5 the output will be as follows.
#OUTPUT : 5 4 3 2 1 0 1 2 3 4 5

#Variable Initialization
k = 0

n = int(raw_input("Enter a Number : "))

#Calculation & Result
i = n + 1
k = k - n

while i != k:
sys.stdout.write("%3d"%(abs(k)))
k += 1


Enter a Number : 3
3  2  1  0  1  2  3

### Example 6.61, Page number: 160

In [68]:
#Enter a number through keyboard and find the sum of the digits.

#Variable Initialization
k = 1
sum1 = 0            #since sum is a built-in function in python, sum1 used instead of sum

n = int(raw_input("Enter a Number : "))

#Calculation
while n != 0:
k = n % 10
sum1 = sum1 + k
k = n / 10
n = k

#Result
sys.stdout.write("Sum of digits %d"%(sum1))


Enter a Number : 842
Sum of digits 14

### Example 6.62, Page number: 161

In [69]:
#Enter few numbers and count the positive and negative numbers together
#with their sums.  When 0 is entered program should be terminated.

#Variable Initialization
p = 0
n = 0
j = 1
s = 0
ns = 0

#Calculation
sys.stdout.write("Enter Numbers (0) Exit : ")
while j != 0:
j = int(raw_input(""))
if j > 0:
p += 1
s = s + j
else:
if j < 0:
n += 1
ns = ns + j

#Result
sys.stdout.write("\nTotal Positive Numbers : %d"%(p))
sys.stdout.write("\nTotal Negative Numbers : %d"%(n))
sys.stdout.write("\nSum of Positive Numbers : %d"%(s))
sys.stdout.write("\nSum of Negative Numbers : %d"%(ns))


Enter Numbers (0) Exit : 1
2
3
4
5
-5
-4
-8
0

Total Positive Numbers : 5
Total Negative Numbers : 3
Sum of Positive Numbers : 15
Sum of Negative Numbers : -17

### Example 6.63, Page number: 162

In [70]:
#Find sum of odd and even numbers separately by sorting the given numbers into
#odd and even numbers

#Variable Initialization
c = 1
odd = 0
even = 0

a = int(raw_input("Enter a Number : "))

#Calculation & Result
sys.stdout.write("ODD     EVEN\n")
while c <= a:
b = c % 2
while b == 0:
sys.stdout.write("\t%d "%(c))
even = even + c
b = 1
b = c % 2
while b != 0:
sys.stdout.write("\n%d"%(c))
odd = odd + c
b = 0
c += 1

sys.stdout.write("\n==============================")
sys.stdout.write("\n %d      %d"%(odd,even))

Enter a Number : 10
ODD     EVEN

1	2
3	4
5	6
7	8
9	10
==============================
25      30

### Example 6.64, Page number: 163

In [71]:
#Print the entered number in reverse order.

#Variable Initialization
x = 1

d = int(raw_input("Enter the number of digits : "))
n = int(raw_input("Enter the number which is to be reversed : -"))

#Calculation & Result
sys.stdout.write("\nThe Reversed Number is :-")

while x <= d:
i = n % 10
sys.stdout.write("%d"%(i))
n = n / 10
x += 1

Enter the number of digits : 4
Enter the number which is to be reversed : -5428

The Reversed Number is :-8245

### Example 6.65, Page number: 163

In [72]:
#Separate capitals, small, symbols and numbers from a statement

import sys

#Variable Initialization
i = 0
c = 0
s = 0
h = 0
n = 0

#Array declaration
scan = [0 for i in range(0,40)]
cap = [0 for i in range(0,20)]
small = [0 for i in range(0,20)]
num = [0 for i in range(0,20)]
oth = [0 for i in range(0,20)]

scan = raw_input("Enter Text Here : ")

i = 0

while i < len(scan):                       #There is no null termination character in python.
if scan[i] >= '0' and scan[i] <= '9':
n += 1
num[n] = scan[i]
else:
if scan[i] >= 'A' and scan[i] <= 'Z':
c += 1
cap[c] = scan[i]
else:
if scan[i] >= 'a' and scan[i] <= 'z':
s += 1
small[s] = scan[i]
else:
h += 1
oth[h] = scan[i]

i += 1

#Result
sys.stdout.write("\nCapital Letters : [")
for i in range(0,20):
sys.stdout.write("%c"%cap[i])

sys.stdout.write("]\nSmall Letters : [")
for i in range(0,20):
sys.stdout.write("%c"%(small[i]))

sys.stdout.write("]\nNumeric Letters : [")
for i in range(0,20):
sys.stdout.write("%c"%(num[i]))

sys.stdout.write("]\nOther Letters : [")
for i in range(0,20):
sys.stdout.write("%c"%(oth[i]))
sys.stdout.write("]")


Enter Text Here : HAVE A NICE DAY, contact me on 51606.

Capital Letters : [HAVEANICEDAY]
Small Letters : [contactmeon]
Numeric Letters : [51606]
Other Letters : [   ,    .]

### Example 6.66, Page number: 165

In [13]:
#Sort numbers, upper and lower case alphabets

import sys

#Variable Initialization
i = 48

#Result
sys.stdout.write("   NUMBERS\n")
while i <= 57:
sys.stdout.write("%2c"%(i))
i += 1

i += 7

sys.stdout.write("\n  CAPITAL ALPHABETS\n")
while i <= 90:
sys.stdout.write("%2c"%(i))
i += 1

i += 6

sys.stdout.write("\n  SMALL ALPHABETS\n")
while i <= 122:
sys.stdout.write("%2c"%(i))
i += 1


   NUMBERS
0 1 2 3 4 5 6 7 8 9
CAPITAL ALPHABETS
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
SMALL ALPHABETS
a b c d e f g h i j k l m n o p q r s t u v w x y z

### Example 6.67, Page number: 165

In [15]:
#Sort numbers, upper and lower case alphabets

import sys

#Variable Initialization
i = 48

#Result
sys.stdout.write("Numbers : ")
while i < 124:
if i < 58:
sys.stdout.write("%2c"%(i))
else:
if i == 58:
sys.stdout.write("\nCapital Letters : ")
i += 7
if i > 64 and i < 91:
sys.stdout.write("%2c"%(i))
if i == 90:
sys.stdout.write("\nSmall Letters : ")
i += 7
if i > 96 and i < 123:
sys.stdout.write("%2c"%(i))
i += 1

Numbers :  0 1 2 3 4 5 6 7 8 9
Capital Letters :  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Small Letters :  a b c d e f g h i j k l m n o p q r s t u v w x y z

### Example 6.68, Page number: 167

In [3]:
#Display all ASCII numbers and their equivalent character, numbers and symbols using while loop.

import sys

#Variable Initialization
i = 64
c = 'Y'

#Result
while c == 'Y':
sys.stdout.write("\t%c (%d)"%(i,i))
i += 1
sys.stdout.write("\nPrint (Y/N)")
c = raw_input("")

	@ (64)
Print (Y/N)	A (65)
Print (Y/N)	B (66)
Print (Y/N)	C (67)
Print (Y/N)

### Example 6.69, Page number: 168

In [73]:
#Convert entered character into its opposite case.

import sys

#Result
sys.stdout.write("\n*Enter 'E' to exit")
sys.stdout.write("\n*Enter only characters")

while c != 'E':
sys.stdout.write("\nEnter a character : ")
c = raw_input("Enter a character :")
if c == c.upper():
c = ord(c)
sys.stdout.write("\tIt's Lower Case : %c"%(chr(c+32)))
else:
c = ord(c)
sys.stdout.write("\tIt's Upper Case : %s"%(chr(c-32)))
c = chr(c)

*Enter 'E' to exit
*Enter only characters
Enter a character : Enter a character :s
It's Upper Case : S
Enter a character : Enter a character :A
It's Lower Case : a
Enter a character : Enter a character :E
It's Lower Case : e

### Example 6.70, Page number: 169

In [11]:
#Print numbers after each iteration and messages after termination of each loop using 3 nested while loop.

import sys

#Variable Initialization
i = 1
j = 1
k = 1

#Result
while i < 4:
while j < 3:
while k < 2:
sys.stdout.write("\n\ni = %d j = %d k = %d"%(i,j,k))
k += 1
sys.stdout.write("\nInner Loop (k) Completed.")
k = 1
j += 1
sys.stdout.write("\nMiddle Loop (j) Completed.")
j = 1
i += 1
sys.stdout.write("\nOuter Loop (i) Completed.")


i = 1 j = 1 k = 1
Inner Loop (k) Completed.

i = 1 j = 2 k = 1
Inner Loop (k) Completed.
Middle Loop (j) Completed.

i = 2 j = 1 k = 1
Inner Loop (k) Completed.

i = 2 j = 2 k = 1
Inner Loop (k) Completed.
Middle Loop (j) Completed.

i = 3 j = 1 k = 1
Inner Loop (k) Completed.

i = 3 j = 2 k = 1
Inner Loop (k) Completed.
Middle Loop (j) Completed.
Outer Loop (i) Completed.

### Example 6.71, Page number: 170

In [13]:
#Display a message "This is a program of do while loop". for 5 times using do while loop.

import sys

#Variable Initialization
i = 1

#Result
#There is no do..while loop in python
while i <= 5:
sys.stdout.write("\nThis is a program of do while loop.")
i += 1

This is a program of do while loop.
This is a program of do while loop.
This is a program of do while loop.
This is a program of do while loop.
This is a program of do while loop.

### Example 6.72, Page number: 171

In [74]:
#Print the entered number in reverse order and find sum and product of digits using do-while loop.

import sys

#Variable Initialization
#since sum is a built-in function in python, sum1 is used instead of sum
x = 1
mul = 1
sum1 = 0

d = int(raw_input("Enter the number of digits : -"))
n = int(raw_input("Enter the number which is to be reversed :-"))

#Result
#There is no do..while loop in python
sys.stdout.write("\nReveresed Number :- ")
while x <= d:
i = n % 10
sys.stdout.write("%d"%(i))
sum1 = sum1 + i
mul = mul * i
n = n / 10
x += 1

sys.stdout.write("\nMultiplication of digits :- %4d"%(mul))

Enter the number of digits : -4
Enter the number which is to be reversed :-4321

Reveresed Number :- 1234
Multiplication of digits :-   24

### Example 6.73, Page number: 172

In [1]:
#Attempt the question 6.72 by considering the false condition i.e. the value of i should
#be initially larger than the value in the while loop.

import sys

#Variable Initialization
i = 7

#Result
#There is no do-while loop in python
sys.stdout.write("\nThis is a program of do while loop")
while i <= 5:
sys.stdout.write("\nThis is a program of do while loop")
i += 1

This is a program of do while loop

### Example 6.74, Page number: 172

In [2]:
#Find the cubes of 1 to 10 numbers using do-while loop.

import sys

#Variable Initialization
x = 1

#Result
sys.stdout.write("\nPrint the numbers and their cubes\n")
while x <= 10:
y = pow(x,3)
sys.stdout.write("%4d %27d\n"%(x,y))
x += 1

Print the numbers and their cubes
1                           1
2                           8
3                          27
4                          64
5                         125
6                         216
7                         343
8                         512
9                         729
10                        1000


### Example 6.75, Page number: 173

In [75]:
#Check whether the given number is prime or not.

import sys

#Variable Initialization
x = 2
n = int(raw_input("Enter The number for testing (prime or not) : "))

#Result
#There is no do-while loop in python
while x < n:
if n % x == 0:
sys.stdout.write("\nThe number %d is not prime."%(n))
exit(0)
x += 1

sys.stdout.write("\nThe number %d is prime"%(n))

Enter The number for testing (prime or not) : 5

The number 5 is prime

### Example 6.76, Page number: 174

In [76]:
#Count the number of students having age less than 25 and weight less than 50Kg out of five.

import sys

#Variable Initialization
count = 0
x = 1

sys.stdout.write("\nEnter data of 5 boys\n")
sys.stdout.write("\nAge Weight\n")

#There is no do-while loop in python
while x <= 5:
age = int(raw_input(""))
wt = float(raw_input(""))
if age < 25 and wt < 50:
count += 1
x += 1

#Result
sys.stdout.write("\nNumber of boys with age < 25")
sys.stdout.write("and weight < 50Kg = %d\n"%(count))

Enter data of 5 boys

Age Weight
24
51
20
45
25
51
20
35
24
54

Number of boys with age < 25and weight < 50Kg = 2


### Example 6.77, Page number: 175

In [77]:
#Compute the factorial of given number using do while loop.

import sys

#Variable Initialization
fact = 1
a = int(raw_input("Enter The Number : "))
sys.stdout.write("\nEnter The Number : %d\n"%(a))

#Calculation
#There is no do-while loop in python
while a >= 1:
sys.stdout.write("%d * "%(a))
fact = fact * a
a -= 1

#Result
sys.stdout.write(" = %d"%(fact))
sys.stdout.write("\nFactorial of Given number is %d"%(fact))

Enter The Number : 5

Enter The Number : 5
5 * 4 * 3 * 2 * 1 *  = 120
Factorial of Given number is 120

### Example 6.78, Page number: 175

In [78]:
#Evaluate the series such as 1+2+3+ .. i. Using do-while loop.

import sys

#Variable Initialization
a = 1
s = 0

i = int(raw_input("Enter a number : "))

#Calculation and Result
#There is no do-while loop in python
while a <= i:
sys.stdout.write("%d + "%(a))
s = s + a
a += 1

sys.stdout.write("\b\bs = %d"%(s))

Enter a number : 5
1 + 2 + 3 + 4 + 5 + s = 15

### Example 6.79, Page number: 176

In [12]:
#Use while statement in do-while loop and print values from 1 to 5

import sys

#Variable Initialization
x = 0

#There is no do-while loop in python
while x < 5:
x += 1
sys.stdout.write("\t%d"%(x))

	1	2	3	4	5
In [ ]: