Loops in Python
Loops in Python
Loops in Python
EXAMPLE :
Step1:
Step1: EXAMPLE :
We need to assign a value with start value with the bigger
value rather than the conditional value so that loop will get while(a>=1)
started or else loop can’t be run through.
print a
Step 2:
counter = 0
For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]
range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
EXAMPLE 2 : FACTORIAL OF A NUMBER
EXAMPLE 1
num = 8
n=4
for i in range(0, n):
factorial = 1
print(i)
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
EXAMPLE 4 : FIBONNACI SERIES
EXAMPLE 3 PRINT TABLE
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
num = 12 The first two terms are 0 and 1. All other terms are obtained by adding the
for i in range(1, 11): preceding two terms. This means to say the nth term is the sum of (n-1)th
print(num, 'x', i, '=', num*i) and (n-2)th term.
Algorithm for printing Fibonacci series using a while loop
Step 1:Input the 'n' value until which the Fibonacci series has to be generated
Step 7:sum = a + b
Step 10:Else
The first two terms are 0 and 1. All other terms are obtained by
adding the preceding two terms. This means to say the nth term is the
sum of (n-1)th and (n-2)th term.
EXAMPLE 1: