Skip to content

Loops in Python

wilsonshamim edited this page Jun 11, 2018 · 2 revisions

Type of Loops:

1. While loop
1. For Loop
1. do… while

Loop Control statements:

  • break statement.: Terminates the loop statement and transfers execution to the statement immediately following the loop.
  • Continue statement : Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
  • Passstatement.: The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
    The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example) −

example
For Loop:
li = [1,2,3,4,5]
for i in li:
print(i)
-—————————
While Loop:
count = 0
while count < 10:
print("count is ",count)
count = count+1
-————————-
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.

Here is the syntax and example of a one-line while clause −

flag = 1
while (flag): print ‘Given flag is really true!’
print “Good bye!”

Pass statement :
for letter in ‘Python’: # First Example
if letter == ‘h’:
pass
print(“kk”)
print(“kkkk”)
print(‘Current Letter :’, letter)
-————————————————————-
Continue Statement:
for letter in ‘Python’: # First Example
if letter == ‘h’:
continue
print(‘Current Letter :’, letter)
-————————————————————-
Break Statement
for letter in ‘Python’: # First Example
if letter == ‘h’:
break
print(‘Current Letter :’, letter)

Clone this wiki locally