Loops in Python
A loop statement uses to
execute a statement or group of statements multiple times as specified by the user.
It’s also called iterations.
Iteration:
- Repetitive execution of the same code block.
Two
types of iteration:
Definite iteration:-
the
number of repetitions is specified explicitly in advance. Ex. For loop
Indefinite iteration:-
the
code block executes until some condition is met. Ex. while loop.
Python provides 2 types of loops:
- While
loop
- For
loop
1) While loop:
It is used to execute multiple statements or codes repeatedly until the
given condition is true.
Use this loop when don’t know the number of times to iterate.
Syntax:
while
expression:
statement(s)
The loop iterates while the
condition is true.
Example
count = 0
while (i < 11):
print 'The count is:', i
i = i + 1
print "count end!"
output:-
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
The count is: 10
count end
Single Statement Suites
Similar to the if statement syntax, while clause consists only of a single statement.
Syntax:
while expression: statement(s)
==================================================================
2) For loop:
For loop execute a block of statements or code several times until the given condition becomes false.
It is iterating over a sequence (either a list, a tuple, a dictionary, a set, or a string).
The syntax
for iterating_var in sequence:
statements(s)
example :-
for letter in 'Python': # First Example print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # Second Example print 'Current fruit :', fruit print "Good bye!" output: Current Letter : P Current Letter : y Current Letter : t Current Letter : h Current Letter : o Current Letter : n Current fruit : banana Current fruit : apple Current fruit : mango Good bye! Example: language = [‘Python’, ‘Java’, ‘Ruby’] for lang in language: print(“Current language is: “, lang) Output: Current language is: Python Current language is: Java Current language is: Ruby =========================================== For loop using range () function: Range () function is used to generate a sequence of numbers. for x in "banana": print(x) output:- b a n a n a ============================================== The break Statement With the break statement we can stop the loop before it has looped through all the items: Example # Exit the loop when x is "banana": fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break Output: apple banana ============================================== The continue Statement With the continue statement we can stop the current iteration of the loop, and continue with the next: Example Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) output: apple banana cherry =================================================== The range() Function range() function use for specified number of times a set of code define. This function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Example #Using the range() function: for x in range(6): print("Using the range() function",x) #Using the start parameter: for x in range(2, 6): print(x) #Increment the sequence with 3 (default is 1): for x in range(2,30, 3): print("Increment the sequence with 3 (default is 1):",x) output:- Using the range() function 0 Using the range() function 1 Using the range() function 2 Using the range() function 3 Using the range() function 4 Using the range() function 5 2 3 4 5 Increment the sequence with 3 (default is 1): 2 Increment the sequence with 3 (default is 1): 5 Increment the sequence with 3 (default is 1): 8 Increment the sequence with 3 (default is 1): 11 Increment the sequence with 3 (default is 1): 14 Increment the sequence with 3 (default is 1): 17 Increment the sequence with 3 (default is 1): 20 Increment the sequence with 3 (default is 1): 23 Increment the sequence with 3 (default is 1): 26 Increment the sequence with 3 (default is 1): 29 Lists as an iterable collection = ['hey', 5, 'd'] for x in collection: print(x) Loop over Lists of lists list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in list_of_lists: for x in list: print(x) ======================================== Nested Loops A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": Example Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) output:- red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry ====================================================================== The pass Statement if a for loop with no content, then use the pass statement to avoid an error. It is used when a statement is required syntactically but do not need 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 code will eventually go, but has not been written yet (e.g., in stubs for example) − Syntax pass Example for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter print "Good bye!" output: − Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye! ==========================================
0 Comments