You are on page 1of 9

142 Chapter 6

numbers.
Pregan A function to find
the sum of two

Program 30: of two


numbers
sum
to find
# a function
def sum(a, b):
print('Sum=, a+b)
5 and 10
call sum() and pass 1.5 and 2.5
sum(5,10)# call sum) and pass
sum(1.5, 2 . 5 ) #

Output:
C:Ppython Demo.py
Sum= 15
Sum= 4.0
the computed resul+
is not returning It is
sum) function
the
In the above program,
In s o m e cases, it is highly usehalt
print) statement.
simply displaying the result using done using return' statemar
the result. This is ment
the function as if it is returning
write value to the calling place
used inside a function to
return s o m e The
return statement is
return statement is:
syntax of using the
return expression
30 such that the sum() function returns the result with the heh
We will rewrite Program
of return statement.

Preta function that returns the result of sum of two


Program 31: A Python program to write a

numbers.

#a function to return sum of two numbers


def sum (a, b):
return a+b # result is returned from here
# call sum() and pass 5 and 10
# get the returned result into res
res Sum(5, 10)
print'The result is ', res)
Output:
C:python Demo.py
The result is 15
When a function does not return ement

anything, then we need not write 'return sla


inside the function.

Once we understand control statements, ams.


we would be ready to develop better pion
In the next program, we want to hecking
display prime numbers. The general logic 10 t0
whether number 'n' is prime or not is to divide 'n' with
a
every number starting i he
n-1. If n' is not divisible by all numbers from 2 to ould
n-1, then it is prime and si can
displayed. On the other hand, if 'n' is divisible
by any number from 2 to n-1, then
, thet
we

say it is not prime and hence it should be left. This logic is used in
Program 32.
Control Statements| 143

rite a Python program to display prime number series.


Program 32: Writ

# program to print prime numbers upto a given number


#accept upto what number the user wants
max int(input("Upto what number? "))

for num in range(2, max+1): generate from 2 onwards till max


for i in range(2,num): 1.represents numbers from 2 to num-1
if (num i) == 0: if num 1s divisible by i
break *then it is not prime, hence go back and check next
number
else:
print(num) #otherwise it is prime and hence display
Output:
c:python primes.py
what number? 30
upto

13
17
19

29
In the previous program, observe the following statements:
if (num % i) == 0: # if num is divisible by i
break

If the number 'num' is not prime then break' is executed. This 'break' statement will
break the inner for loop and Python interpreter goes back to outer for loop where the next
number comes into num'. The reader is urged to understand the indentation of the
statements in the program without confusion.

Let's writ a program to display Fibonacci numbers. The Fibonacci number series are
given as: 0, 1, 1, 2,3, 5, 8, 13, 21, 34, etc. If we take the first two Fibonacci numbers as:

Then the third Fibonacci f can be obtained by adding the two previous Fibonacci
numbers as:
f fl+ f2
NOw, the two recent Fibonacci numbers are f2 and f. So, to get the next Fibonacci
number, we should add them by taking them as f1 and f2. It means,
f2 # take f2 as f1
f # take f as f2
f fl+ f2 # get next Fibonacci number
144 Chapter6
generat.
Figure
6.3. To repeatedly te the Fibo
in
represented
The above logic is in a loop as:

can use
the a b o v e logic
we
numbers,

while c<f f1+f2


print(f)

f1-f2
f2-f
C + - 1 # increment count

1 1 2 33 5

f1 f2 f
f1 f 2
f2 f
f f1+ f2

6.3: Logic to generate Fibonacci numbers


Figure

Paonam number series.


Progranm 33: Write a Python program to generate Fibonacci
#program to display Fibonacci series
? '))
n =int(input("How many Fibonaccis
f1-0
f2-1
# this is first Fibonacci
# this is the second one
no

counts the no off Fibonaccis


if n=l:
print(f1)
elif n==2:.
print(f1, '\n', f2, sep=' ')
el se
print(f1, '\n', f2, sep='')
while C<n:
f f1+f2 # add two Fibonaccis to get the new one
print(F)
f1, f2 f2, f # this is same as f1-f2, f2=f
C+=1 # increment counter

Output:
C:\>python fibo.py
How many Fibonaccis ? 10
0
1

13
21
34
Control Statements 145

tet's write a Python program


to find Sine value of a given angle using Sine series. Sine
the following formula:
series is represented by

sin x x

In the above formula, x' value is assumed to be in radians. If the user inputs the angle
ralue in radians, then it can be used in the above formula directly. But if the user inputs
radians. To convert into
the angle value in degrees, then it should be converted into
radians, we should multiply degrees value by 3.14159/180 as:

r x *3.14159/180
This becomes the first term. So, let's take it as t'.
t r

term contains
Now, we want to find out the second term. Please observe that the
second
the first term. So, the second term can be written as:

= 2 t i(i+1)
where t represents the previous term and i value is taken as 2. Similarly, the third term
contains the second term.

5! 3! 4*5 i*(i+1)
where t represents the previous term. Here i' value will be 4. So, each new term in the
series can be obtained by the following expression:
t= (-1) *t *r* r/(i (i + 1))
The -1 in the beginning of the preceding expression represents alternate positive and
negative terms in the formula. This expression is used in the Program 34. This program
accepts the angle value in degrees from the user and finds the Sine of that angle value.
This program also accepts the number of iterations from the user. If the number of
iterations is limited like 3 or 4, then the accuracy may not be good. Hence the user
should give 10 to 15 iterations so that acurate result can be obtained.

Pnoyam
Program 34: Write a Python program to calculate the Sine value of a given angle in
degrees by evaluating Sine series.

#program to evaluate Sine series.


# user input
X, accept
n =int(i) fori in input("Enter angle value, no. of iterations
").split(,')]
146 Chapter 6

into rad1ans
from degrees
#Convert the angle
r=(x*3. 14159)/180
first term
# this becomes the
t=r

# til1 now, find the sum

sum=r iteration number and sum


#display the % (1, sum))
print"Iteration= %d\tsum= %f
second term
# denominator for the
i=2
nth terms
# repeat for 2nd to

for j in range (2, n+1:. # find the next termn


t=(-1)*t*p*r/(i*(i+1))
# add i t to sum
sum=sum+t; sum)D)
% (j,denominator
print('Iteration= %d\tsum= %f" for next term
# increase i value by 2
for rm
i +=2

Output:
C:\>python sine.py
Enter angle value, no. of iterations: 60, 10
Iteration= 1 Sum= 1.047197
Sum= 1.855800
Iteration= 2
Iteration= 3 Sum= 1.866295
Iteration= 4 Sum= 1.866021
Iteration= 5 Sum= 1.866025
Iteration= Sum= 1.866025
Iteration= 7 Sum= 1.866025
Iteration= 8 Sum= 1.866025
Iteration= 9 Sum= .866025
Iteration= 100 Sum= 1.866025
If we observe the output, from 5th iteration onwards, the sum value has been stabilized
This value should be taken as the Sine of 60 degrees. So, sin(60) = 1.866025.

Similarly, we can write another program for finding the value of Cosine series. The
formula for Cosine series is

2
cosX 1 2! 4!
.

6!
To find the value of cosine series, we take the first term as 1 and the sum value as i
a
Sum 1
We can imagine the second term as:

x2 2
= 1* t
2! 1 (2) i (i+1)
Control Statements 147

here t represents the previous term, i.e. 1 and i value is 1. In the same manner, the
term c a n be:
third

x x2 2

41 21 3 (4)
1 (1+1)
where t' represents the previous terms and I value is 3. In this way we can find the terms
in the series and add them to 'sum which is initially "1'. So, cach term in the s
be obtained using the following expression:
t(-1)*tr**2/(iMCi+1))
The beginning ( -1) helps to generate the positive and negative terms alternately. This
logic is shown in Program 35.

Protam
Program 35: Write a Python program to find Cosine value of a given angle in degrees by
evaluating the Cosine series.
#program to evaluate Cosine series.
accept user input
X, n =int(1) for.i.in input("Enter angle value, no. of iterations:
").split(",')]

#convert. the angle from degrees into radians


r=(X*3. 14159)/180
# this becomes the first term
t-1

#till now, sum is 1 only


sum=1

# display the iteration number and sum


print('Iteration= %d\tsum= %f % (1, sum))

# denominator for the second term


i=1

# repeat for 2nd to nth terms

for j in range(2, n+1)


t=(-1)*tfr**2/(i*(i+1)) # find the next term
sum-sum+t; # add it to sum
printC'Iteration= %d\tsum= %F % (j,, sum))
i +=2 # increase i value by 2 for denominator for next term

Output:
C:\>python cos.py
Enter angle value, no. of iterations: 60, 10
Iteration= 1 Sum= 1.000000
Iteration= Sum= 0.451690
Iteration= 3 Sum= 0.501797
Iteration= 4 Sum= 0.499965
148 Chapter 6

Iteration= 5 Sum= 0.500001


teration= Sum= 0.500001
Iteration= Sum= 0.500001
Iteration= Sum= 0. 500001
Iteration= Sum 0. 500001
Iteration= 10 Sum= 0. 500001
Observe the output of the previous program. From 5h iteration
stabilized. Hence we can say cos(60) = 0.500001.
onwards, the
esult has
Similarly, we can construct logic for finding the value
represented by the following formula:
of Exponential series
which is

3
To find the value of
1 as:
Exponential series, we take the first term as 1 and the sum val..
ueas
t 1
Sum = 1

We can
imagine the second term, as:

X
1.
1! 1*1
where j' value is 1'. Now
the third term can be written as:

2!
where t
represent the previous terms and j value
incremented by 1' for each new
will be 2'. Thus values are
term. This
logic is shown in
Program 36.
Program
Program 36: Write a Python
program to evaluate
# program to
evaluate exponential series.
#accept
X, n
user input Exponential series.
int(i) for i in input(C"Enter
").splitC,')] power of e, of
# this becomes the
no.
iterations
t=1 first term
# til1 now, sum is 1
Sum=t only
# display
iteration the
print'Iteration= number
%d\tsum= %F" and sum
% (1,
# sum)))
repeat for lst to n-1th
terms
Control Statements 149
for i in range(1 n):
# find the next term
Sum Sum+t; #add it to sum
printC'Iteration= %d\tsum= %F" % (j+1, sum))
Output:
C:\>python eval.py
Enter power of e, no.
Iteration= 1
otf iterations: 2, 15
Sum 1.0000000
Iteration= 2 Sum 3.000000
Iterati on= 3 Sum 5.000000
Iteration= 4 Sum- 6.333333
Iteration= 5 Sum= 7.000000
Iteration= 6 Sum= 7.266667
Iteration= 7 Sum= 7.355556
Iteration= 8 Sum= 7.380952
Iteration= 9 Sum= 7.387302
Iteration= 10 Sum= 7.388713
Iteration= 11 Sum= 7.388995
Iteration= 12 Sum= 7.389046
Iteration= 13 Sum= 7.389055
Iterati on= 14 Sum= 7.389056
Iteration= 15 Sum= 7.389056

Points to Remember
Control statements are statements that control the flow of execution of
statements so
that they can be executed
repeatedly and randomly.
The if statement executes a
group of statements depending upon whether a condition
is True or False.

The difference between statement and


a
loop is that the statement is executed only
once but a loop be executed
can
repeatedly. Python offers for and while loops for
repeated execution.
Indentation represents the spaces before a statement
that identifies the statement as
belonging to a block. The default indentation in Python is 4 spaces.
The for loop is generally used to iterate the elements
over
of a sequence like a string,
a list or tuple.

aIt is possible 'else suite' along


to use with loops.
I t is possible to write one loop inside another loop. Such loops are called 'nested
loops.
A n infinite loop is a loop that is executed forever. Using infinite loops in a program is
not advisable.

T h e break statement is useful to come out of a loop.


150 Chapter 6
The continue statement is useful to continue with the next repetition of a loon

The pass statement does nothing and hence used to send execution to th
next
statement.
T h e assert statement is useful to check if a particular condition is fulfilled or nes
not. I
he condition is not fulfilled then it will raise Assertion Brror. lts general format i
assert expression, message'
T h e return statement is used in a function to return some value from the function

You might also like