0% found this document useful (0 votes)
29 views5 pages

Unit-4 Loops

Uploaded by

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

Unit-4 Loops

Uploaded by

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

Unit-4 Loops

Python Programming
For Loop
• Syntax:
• for variables in ittereable
• Eg:
• for i in range(10)
• for i in range (1,10)
• for i in x ; x=‘hello’, x=[1,2,3,4]
• for i in range(len(x))
• for i,j in enumerate(x)
• for i, j in zip(x,y) ; x and y must be of same length
For Loop with else
• Eg:
• digits = [0, 1, 5]
• for i in digits:
• print(i)
• else:
• print("No items left.")

• A for loop can have an optional else block as well. The else part is executed if the
items in the sequence used in for loop exhausts.
• The break keyword can be used to stop a for loop. In such cases, the else part is
ignored.
• Hence, a for loop's else part runs if no break occurs.
While Loop
• Syntax:
• while condition
• Eg:
• n = 10
• # initialize sum and counter
• sum = 0
• i=1
• while i <= n:
• sum = sum + i
• i = i+1
while Loop with else
• Eg:
• counter = 0
• while counter < 3:
• print("Inside loop")
• counter = counter + 1
• else:
• print("Inside else")
• Same as for loop while can have else part. The else part is executed if the condition
in the while loop evaluates to False.
• The break keyword can be used to stop loop. In such cases, the else part is ignored.
• Hence, a while loop's else part runs if no break occurs.

You might also like