0% found this document useful (0 votes)
2 views2 pages

Python Chapter (4)Looping

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Python Chapter (4)Looping

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Looping

A loop in Python is a type of control structure that allows a program to repeat a certain block of code a certain
number of times or while a certain condition is true.

Python supports two types of loops: the for loop and the while loop.

for loop

The for loop is used to iterate over a sequence of values and execute a block of code for each value in the
sequence.

(Syntax)

for variableName in (start,end,step):

Statement

Example (1)

for i in range(1,6,1):
print("Hello",i)

Example (2)

str="Hello"
for i in range(0,5,1):
print(str[i])

Example (3)

str="Disney"
newStr=""
for c in str:
newStr+=c+" "
print(newStr)
Example (4)

text="Scoppy"
strNum=""
for i in range(5,-1,-1):
strNum+=text[i]+"\t"
print(strNum)

While loop

The while loop is used to execute a block of code repeatedly until the condition becomes false.

(Syntax)

start
while(end/condition):
Statement
Step(inc/dec)
Example (5)

i=1
while(i<=5):
print(i)
i=i+1

Example (6)

i=10
while(i>=1):
print(i)
i-=2
Example (7)

i=int(input("Enter Number"))
while(i != 0):
print(i*i)
i=int(input("Enter Number"))

Break & Continue


Example (8)

Example (9)

Nested Loop

for( outer loop )row / col


for( inner loop )col / row

for 1 to 5
for 1 to 5
Example (10)

for i in range(1,6):
str1=""
for j in range(1,6):
str1+="* "
print(str1)

Exercise

Write a program to use the loop to find the factorial of a given number. eg.(5! => num=5)

You might also like