n04 PDF
n04 PDF
n04 PDF
statement/s in a loop.
The colon (:) must follow the test-condition i.e. the while statement is terminated
with colon(:)
The statement(s) within while loop will be executed till the condition is true
Flow chart of While Loop
Program on While Loop
Program to print the numbers from one to five using
while loop
>>> list(range(1,6))
[1,2,3,4,5]
To create a list of integers from 1 to 20 with a difference of
2 between two successive integers
>>> list(range(1,20,2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
The for loop
Python for loop iterates through a sequence of objects i.e.
it iterates through each value in a sequence.
Output
0 1 2 3 4
The break Statement
The keyword break allows the programmer to terminate the loop.
When the break statement is encountered inside a loop, the loop
is immediately terminated and program control automatically
goes to the first statement.
Flow chart of break statement
Working of break in while and for loop
while test-Boolean-expression:
body of while
if condition:
break
body of while
Statement(s)
if condition:
continue
body of while
Statement(s)
print(“Star Pattern”)
num=1
x=num
for i in range(1,6,1):
num=num+1
for j in range(1,num,1):
print(“ * ”,end=”
“)
x=num+1
print()
# Write a program to display the
pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
print(“Number Pattern”)
num=1
x=num
for i in range(1,6,1):
num=num+1
for j in range(1,num,1):
print( j ,end=” “)
x=num+1
print()
#Use of Break statement
print(“Print number from 1 to 100 in :”)
for i in range(1,100,1):
if(i ==11):
break
else:
print(i,end=” “)
#chek the number is prime or not
num=int(input(“Enter a number”))
x=num
for i in range(2,num):
if(num%i ==0):
flag=0
break
else:
flag=1
if(flag==1):
print(num,”prime”)
else:
print(num,” not prime”)
#Use of Continue
for i in range(1,11,1):
if i==5:
continue
print(i,end=” “)