Computer Science2 New12th Class
Computer Science2 New12th Class
.
UNIT- 1
CONTROL STRUCTURES IN PYTHON
LOOPS
Types of loops:
1. for loop
2. While loop
Syntax
Initialization
while <test expression>:
Statements
i= 1 //initialization
while i< 6: //test expression
print (i) // iteration stmt
i=i+1 // update condition
Output
1 2 3 4 5
Output
enter the limit of natural Nos
= 5
1 2 3 4 5
sum of 1st 5 natural Nos = 15
2.for loop
A for loop is used for iterating over a
sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
Syntax:
for < variable > in <sequence>:
Statements to repeat:
Output :
1
4
7
// program
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
output:
apple
banana
cherry
Output will be 1 2 3 4
Output:
enter any No.= 5
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
Sum=0
for n in range(1,11):
print(n)
sum =sum +n
print(“sum of natural Nos from 1 to 10 =”’sum)
sum = 0
a=int(input("enter limit of series ="))
n=1
while n<=a:
sum=sum+n
print(n)
n=n+1
print("sum of natural Nos=",sum)