Python while loop examples | applied electronics engineering

Python while loop examples

By Applied Electronics - Monday, July 18, 2016 No Comments
Like any other programming language, python programming language supports the while loop. There are number of application where a while loop can be used. It can be for example used to check a certain condition and do something until the condition is satisfied. Or it can be used in iterative processing such as doing summation.

A while statement in python to print out something until a condition is satisfied.

#while loop example

x = 0

while x<=10:
print(x)
x = x+2

The output of this loop is as follows:

0
2
4
6
8
10

While loop are useful to do iteration and summation in mathematics are iterations. The following example shows how one can use the while loop to do summation upto 25 terms for the calculation of sin(x) polynomial.

The sin(x) polynomial is given by:

# using while loop for Summation

import math

x = float(input("enter a number: "))

sinx = x
N = 30

k = 1
sgn = 1

while k < N:
sgn = -sgn
k = k+2
term = sgn*(x**k)/math.factorial(k)
sinx = sinx + term

print("sin(x=%f) is %f" %(x, sinx))

The output for this python code is as follows:

enter a number: 1.2
sin(x=1.200000) is 0.932039