# Chapter 4: Control Structures¶

## Example if1.c, page no. 101¶

In [3]:
i = int(raw_input("Enter a number: "))
if i % 3 == 0 :
print "Number entered is divisible by 3."

Enter a number: 30
Number entered is divisible by 3.


## Example scanf8.c, page no. 102¶

In [1]:
#The output in the textbok is 0.000000 because it was not able to convert string to float in C
#Hence, by default it stored 0.0000000. In Python the same would give error. Hence, the answer differs

years = float(raw_input("Input your age in years: "))
secs = years * 365 * 24 * 60 * 60
print "You have livid for %f seconds " %secs

Input your age in years: 25
You have livid for 788400000.000000 seconds


## Example if2.c, page no. 102¶

In [20]:
#the way it is given in textbook is not possible in Python. Doing it in different manner

print "Input your age in years: ",
years =(raw_input())
try:
float(years)
secs = float(years) * 365 * 24 * 60 * 60
print "you have lived for %f seconds" %secs
except:
print "the input is not a floating-point number"

Input your age in years: 75
you have lived for 2365200000.000000 seconds


## Example if3.c, page no. 103¶

In [21]:
#the program will remain same as the previous one

print "Input your age in years: ",
years =(raw_input())
try:
float(years)
secs = float(years) * 365 * 24 * 60 * 60
print "you have lived for %f seconds" %secs
except:
print "the input is not a floating-point number"

Input your age in years: sundeep
the input is not a floating-point number


## Example large.c, page no. 105¶

In [1]:
print "Input a b c"
a = float(raw_input("a="))
b = float(raw_input("b="))
c = float(raw_input("c="))
big = a
if b>big :
big = b
if c>big :
big = c
print "Largest of the three numbers = %7.2f" %big

Input a b c
a=10
b=20
c=45
Largest of the three numbers =   45.00


## Example ifelse1.c, page no. 105¶

In [22]:
#the program will remain same as the previous one

print "Input your age in years: ",
years =(raw_input())
try:
float(years)
secs = float(years) * 365 * 24 * 60 * 60
print "you have lived for %f seconds" %secs
except:
print "the input is not a floating-point number"

Input your age in years: 100
you have lived for 3153600000.000000 seconds


## Example ifelse2.c, page no. 107¶

In [8]:
input1 = int(raw_input("Input an integer: "))
if input1 :
print "It is non-zero."
else :
print "it is zero."

Input an integer: 12
It is non-zero.


## Example scope.c, page no. 112¶

In [23]:
#The block given in the textbook is not possible in Python. Here the value will remain the same.

i = 10
print "In main. i is %d " %i
i = 20
print "In compound statement. i is %d" %i
i = i+1
print "After incrementing: i is %d" %i
print "In main again. i is %d" %i

In main. i is 10
In compound statement. i is 20
After incrementing: i is 21
In main again. i is 21


## Example for.c, page no. 113¶

In [26]:
for i in range(1, 11):
print i*5,

5 10 15 20 25 30 35 40 45 50


## Example sumsq1.c, page no. 115¶

In [27]:
sum = 0
sum_of_squares = 0
for i in range(2, 31, 2):
sum += i
sum_of_squares += i*i
print "Sum of first 15 positive even numbers = ", sum
print "Sum of their squares = ", sum_of_squares

Sum of first 15 positive even numbers =  240
Sum of their squares =  4960


## Example sumsq2.c, page no. 116¶

In [29]:
sum = 0
sum_of_squares = 0
for i in range(30, 1, -2):
sum += i
sum_of_squares += i*i
print "Sum of first 15 positive even numbers = ", sum
print "Sum of their squares = ", sum_of_squares

Sum of first 15 positive even numbers =  240
Sum of their squares =  4960


## Example for2.c, page no. 116¶

In [30]:
for i in range(1, 11):
print 5*i,

5 10 15 20 25 30 35 40 45 50


## Example 4.1, page no. 117¶

In [33]:
#error in textbook, i should be initialized by 1

sign = 1
print "Input X and N: "
x = float(raw_input("X: "))
n = int(raw_input("N: "))
x *= 3.1412/180.0
sum, t = x, x
for i in range(1, n):
sign *=-1
t = sign * x * x / (2*i*(2*i+1))
sum += t
print "SIN(X) = %6.2f" %sum

Input X and N:
X: 60
N: 12
SIN(X) =   0.90


## Example 4.2, page no. 118¶

In [34]:
num = 0
sum = 0
print "Input the marks, -1 at the end"
i = int(raw_input())
while i != -1:
sum += i
num += 1
i = int(raw_input())
average = sum / num
print "The average is %.2f" %average

Input the marks, -1 at the end
12
14
16
18
-1
The average is 15.00


## Example binary.c, page no. 120¶

In [5]:
binary = raw_input("Input the binary number: ")
decimal = int(binary, 2)
print "The decimal equivalent of binary number %s is %d" %(binary, decimal)

Input the binary number: 1101
The decimal equivalent of binary number 1101 is 13


## Example dowhile.c, page no. 122¶

In [7]:
#there is no do while loop in Python. We will use simple while loop
inchar = ''
while(inchar != 'y' and inchar != 'n'):
inchar = raw_input("Input y or n: ")
if inchar == 'y':
print "you pressed y."
if inchar == 'n':
print "you pressed n"

Input y or n: j
Input y or n: j
Input y or n: n
you pressed n


## Example 4.4, page no. 123¶

In [11]:
num = int(raw_input("Input the number: "))
n = num
sum = 0
rev = 0
while(num != 0):
digit = num % 10
sum += digit
rev = rev * 10 + digit
num /= 10
print "Sum of the digits of the number = %4d" %sum
print "Reverse of the number = %7d" %rev
if n == rev:
print "The number is a palindrome"
else:
print "The number is not a palindrome"

Input the number: 1221
Sum of the digits of the number =    6
Reverse of the number =    1221
The number is a palindrome


## Example iflese.c, page no. 127¶

In [12]:
print "Choice of destinations: "
print "\t1 - Mercury"
print "\t2 - Venus"
print "\t3 - Mars"
choice = int(raw_input("Enter the number corresponding to your choice: "))
if choice == 1:
print "Mercury is closest to the sun."
print "So the weather may be quite hot there."
print "The journey will cost you 5200 IGCs."
elif choice == 2:
print "Venus is the second planet from the sun."
print "The weather may be hot and poisonous."
print "The journey will cost you 3200 IGCs."
elif choice == 3:
print "Mars is the closest planet to the earth."
print "The weather has been excellent till now."
print "The journey will cost you 1200 IGCs."
else:
"Unknown destination. Unpredictable IGCs"
print "Note: IGC = Ingeer-Galactic Currency"

Choice of destinations:
1 - Mercury
2 - Venus
3 - Mars
Enter the number corresponding to your choice: 2
Venus is the second planet from the sun.
The weather may be hot and poisonous.
The journey will cost you 3200 IGCs.
Note: IGC = Ingeer-Galactic Currency


## Example 4.5, page no. 128¶

In [14]:
#there is no switch case in Python, hence, no use of break in if conditions. So, the program will remain same

print "Choice of destinations: "
print "\t1 - Mercury"
print "\t2 - Venus"
print "\t3 - Mars"
choice = int(raw_input("Enter the number corresponding to your choice: "))
if choice == 1:
print "Mercury is closest to the sun."
print "So the weather may be quite hot there."
print "The journey will cost you 5200 IGCs."
elif choice == 2:
print "Venus is the second planet from the sun."
print "The weather may be hot and poisonous."
print "The journey will cost you 3200 IGCs."
elif choice == 3:
print "Mars is the closest planet to the earth."
print "The weather has been excellent till now."
print "The journey will cost you 1200 IGCs."
else:
"Unknown destination. Unpredictable IGCs"
print "Note: IGC = Ingeer-Galactic Currency"

Choice of destinations:
1 - Mercury
2 - Venus
3 - Mars
Enter the number corresponding to your choice: 3
Mars is the closest planet to the earth.
The weather has been excellent till now.
The journey will cost you 1200 IGCs.
Note: IGC = Ingeer-Galactic Currency


## Example 4.6, page no. 130¶

In [3]:
print "Input a b & c"
a = float(raw_input("a: "))
b = float(raw_input("b: "))
c = float(raw_input("c: "))
if a != 0:
disc = b * b - 4 * a * c
print "Discriminant = %5.2f" %disc
if disc < 0:
k = 1
elif disc == 0:
k = 2
elif disc > 0:
k = 3
if k == 1:
print "Roots are imaginary"
real = -b/(2*a)
disc = -disc
num = pow(disc, 0.5)
imag = num/(2*a)
print "Root1 = %5.2f +j %5.2f" %(real, imag)
print "Root2 = %5.2f -j %5.2f" %(real, imag)
elif k == 2:
print "Roots are real equal"
root1 = -b/(2*a)
print "Root1 = Root2 = %7.2f" %root1
elif k == 3:
print "Roots are real and unequal"
root1 = (-b + sqrt(disc))/(2*a)
root2 = (-b - sqrt(disc))/(2*a)
print "Root1 = %7.2f Root2 = %7.2f" %(root1, root2)
else:
print "Equation is linear"

Input a b & c
a: 1
b: 2
c: 7
Discriminant = -24.00
Roots are imaginary
Root1 = -1.00 +j  2.45
Root2 = -1.00 -j  2.45


## Example 4.7, page no. 132¶

In [28]:
sum = 0
for i in range(5):
num = int(raw_input("Enter an integer: "))
if num < 0:
print "You have entered a negative number"
continue
sum += num
print "The sum of positive integers entered = ", sum

Enter an integer: 10
Enter an integer: -15
You have entered a negative number
Enter an integer: 15
Enter an integer: -100
You have entered a negative number
Enter an integer: 30
The sum of positive integers entered =  55


## Example 4.8, page no. 133¶

In [31]:
print "Input X & N"
x = float(raw_input("X: "))
n = int(raw_input("N: "))
t = 1
sum = 1
for i in range(1, n):
ifact = i
t = t*x/ifact
sum +=t
print "E raies to power x = %10.4f" %sum

Input X & N
X: 1.00
N: 2
E raies to power x =     2.0000


## Example 4.9, page no. 134¶

In [33]:
n = int(raw_input("Enter the number: "))
if n == 0:
print "The factorial of 0 is 1"
else:
fact = 1
for i in range(1, n+1):
fact = fact * i
print "Factorial of %4d is %5d" %(n, fact)

Enter the number: 5
Factorial of    5 is   120


## Example 4.10, page no. 135¶

In [3]:
binom = 1
q = 0
p = int(raw_input("Input the number of rows: "))
print "Pascal Triangle"
while q < p:
for r in range(40-3*q, 0, -1):
print " ",
for x in range(0, q+1):
if x == 0 or q == 0:
binom = 1
else:
binom = (binom*(q-x+1))/x
print "%6d" %binom,
print "\n"
q+=1

Input the number of rows: 9
Pascal Triangle
1

1      1

1      2      1

1      3      3      1

1      4      6      4      1

1      5     10     10      5      1

1      6     15     20     15      6      1

1      7     21     35     35     21      7      1

1      8     28     56     70     56     28      8      1



## Example 4.11, page no. 136¶

In [47]:
import math

print "Enter 1 for triangle(3 sides) & 2 for triangle(base, ht): ",
k = int(raw_input())
if k == 1:
print "Enter 3 sides - a,b and c"
a = float(raw_input("a: "))
b = float(raw_input("b: "))
c = float(raw_input("c: "))
p = a + b + c
s = (a + b + c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print "Perimeter = %6.2f" %p
print "Area of triangle = %7.2f" %area
elif k == 2:
print "Enter height and base"
height = float(raw_input("height: "))
base = float(raw_input("base: "))
area = (base*height)/2
print "Area of triangle = %7.2f" %area

Enter 1 for triangle(3 sides) & 2 for triangle(base, ht): 1
Enter 3 sides - a,b and c
a: 4.55
b: 5.00
c: 6.00
Perimeter =  15.55
Area of triangle =   11.11


## Example 4.12, page no. 137¶

In [3]:
import sys
print "Enter the no of lines in the pyramid: "
t = int(raw_input())
print "\t\tREVERSED PYRAMID OF DIGITS"
k = 0
for p in range(t, 0, -1):
k += 1
sys.stdout.write ("   ")
for r in range(0, (k*4)+1):
sys.stdout.write (" ")
for q in range(p, (2*p)-1):
sys.stdout.write ("%4d" %q)
for s in range((2*p)-2, p-1, -1):
sys.stdout.write("%4d\b" %s)
sys.stdout.write ("\n")
print  "                                 %d" %p

Enter the no of lines in the pyramid:
7
REVERSED PYRAMID OF DIGITS
7   8   9  10  11  12  12  11  10   9   8   7
6   7   8   9  10  10   9   8   7   6
5   6   7   8   8   7   6   5
4   5   6   6   5   4
3   4   4   3
2   2

1


## Example 4.13, page no. 137¶

In [62]:
import math

n = 20
x = float(raw_input("Input x: "))
x = x*3.1412/180
t = 1
sum = 1
for i in range(1, n+1):
t = t*pow(-1, (2*i-1))*x*x/(2*i*(2*i-1))
sum += t
print "COS(X) = %7.3f" %sum

Input x: 90.00
COS(X) =   0.000


## Example 4.14, page no. 138¶

In [67]:
n = int(raw_input("Enter the number of lines: "))
for p in range(1, n+1):
for i in range(1, n-p):
print "     ",
m = p
for q in range(1, p+1):
print "%4d" %m,
m +=1
m = m - 2
for q in range(1, p):
print "%4d" %m,
m-=1
print "\n\n"

Enter the number of lines: 7
1

2    3    2

3    4    5    4    3

4    5    6    7    6    5    4

5    6    7    8    9    8    7    6    5

6    7    8    9   10   11   10    9    8    7    6

7    8    9   10   11   12   13   12   11   10    9    8    7