Python Loop
Python Loop
The following loops are available in Python to fulfil the looping needs. Python offers 3
choices for running the loops. The basic functionality of all the techniques is the same,
although the syntax and the amount of time required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a loop command.
The following sorts of loops are available in the Python programming language.
2 For This type of loop executes a code block multiple times and
loop abbreviates the code that manages the loop variable.
Python provides the following control statements. We will discuss them later in detail.
2 Continue This command skips the current iteration of the loop. The
statement statements following the continue statement are not executed
once the Python interpreter reaches the continue statement.
In this case, the variable value is used to hold the value of every item present in the
sequence before the iteration begins until this particular iteration is completed.
Loop iterates until the final item of the sequence are reached.
Code
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
Only if the execution is complete does the else statement comes into play. It won't be
executed if we exit the loop or if an error is thrown.
Code
Output:
P
y
t
h
If block
n
L
If block
If block
p
Syntax:
Code
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10. # giving an else statement
11. else:
12. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple
We can give specific start, stop, and step size values in the manner range(start, stop, step
size). If the step size is not specified, it defaults to 1.
Since it doesn't create every value it "contains" after we construct it, the range object can
be characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is
not an iterator.
Code
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method in for loops. We
can use indexing to iterate through the given sequence by combining it with an iterable's
len() function. Here's an illustration.
Code
1. # Python program to iterate over a sequence with the help of indexing
2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition
changes to false.
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code block. These
statements are intended with the same number of spaces. Python groups statements
together with indentation.
Code
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code
1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
Code
Continue Statement
It returns the control to the beginning of the loop.
Code
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.
Code
Output:
Last Letter: s
Python for loop
Python is a strong, universally applicable prearranging language planned to be easy to
comprehend and carry out. It is allowed to get to because it is open-source. In this tutorial,
we will learn how to use Python for loops, one of the most fundamental looping
instructions in Python programming.
The value is the parameter that determines the element's value within the iterable
sequence on each iteration. When a sequence contains expression statements, they are
processed first. The first element in the sequence is then assigned to the iterating variable
iterating_variable. From that point onward, the planned block is run. Each element in the
sequence is assigned to iterating_variable during the statement block until the sequence
as a whole is completed. Using indentation, the contents of the Loop are distinguished
from the remainder of the program.
1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over the list
10. for num in numbers:
11.
12. sum_ = sum_ + num ** 2
13.
14. print("The sum of squares is: ", sum_)
Output:
Code
1. my_list = [3, 5, 6, 8, 4]
2. for iter_var in range( len( my_list ) ):
3. my_list.append(my_list[iter_var] + 2)
4. print( my_list )
Output:
[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]
1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over list
10. for num in range( len(numbers) ):
11.
12. sum_ = sum_ + numbers[num] ** 2
13.
14. print("The sum of squares is: ", sum_)
Output:
The len() worked in a technique that profits the complete number of things in the rundown
or tuple, and the implicit capability range(), which returns the specific grouping to
emphasize over, proved helpful here.
After the circuit has finished iterating over the list, the else clause is combined with a for
Loop.
The following example demonstrates how to extract students' marks from the record by
combining a for expression with an otherwise statement.
Code
Output:
Nested Loops
If we have a piece of content that we need to run various times and, afterward, one more
piece of content inside that script that we need to run B several times, we utilize a "settled
circle." While working with an iterable in the rundowns, Python broadly uses these.
Code
1. import random
2. numbers = [ ]
3. for val in range(0, 11):
4. numbers.append( random.randint( 0, 11 ) )
5. for num in range( 0, 11 ):
6. for i in numbers:
7. if num == i:
8. print( num, end = " " )
Output:
0 2 4 5 6 7 8 8 9 10
Python While Loops
In coding, loops are designed to execute a specified code block repeatedly. We'll learn
how to construct a while loop in Python, the syntax of a while loop, loop controls like
break and continue, and other exercises in this tutorial.
If we don't know how many times we'll execute the iteration ahead of time, we can write
an indefinite loop.
Now, here we discuss the syntax of the Python while loop. The syntax is given below -
1. Statement
2. while Condition:
3. Statement
The given condition, i.e., conditional_expression, is evaluated initially in the Python while
loop. Then, if the conditional expression gives a boolean value True, the while loop
statements are executed. The conditional expression is verified again when the complete
code block is executed. This procedure repeatedly occurs until the conditional expression
returns the boolean value False.
Example
Now we give some examples of while Loop in Python. The examples are given in below -
Program code 1:
Now we give code examples of while loops in Python for printing numbers from 1 to 10.
The code is given below -
1. i=1
2. while i<=10:
3. print(i, end=' ')
4. i+=1
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
1 2 3 4 5 6 7 8 9 10
Program Code 2:
Now we give code examples of while loops in Python for Printing those numbers divisible
by either 5 or 7 within 1 to 50 using a while loop. The code is given below -
1. i=1
2. while i<51:
3. if i%5 == 0 or i%7==0 :
4. print(i, end=' ')
5. i+=1
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
Program Code:
Now we give code examples of while loops in Python, the sum of squares of the first 15
natural numbers using a while loop. The code is given below -
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Provided that our counter parameter i gives boolean true for the condition, i less than or
equal to num, the loop repeatedly executes the code block i number of times.
Next is a crucial point (which is mostly forgotten). We have to increment the counter
parameter's value in the loop's statements. If we don't, our while loop will execute itself
indefinitely (a never-ending loop).
Program Code:
Now we give code examples of while loops in Python for a number is Prime number or
not. The code is given below -
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Program Code:
Now we give code examples of while loops in Python for a number is Armstrong number
or not. The code is given below -
1. n = int(input())
2. n1=str(n)
3. l=len(n1)
4. temp=n
5. s=0
6. while n!=0:
7. r=n%10
8. s=s+(r**1)
9. n=n//10
10. if s==temp:
11. print("It is an Armstrong number")
12. else:
13. print("It is not an Armstrong number ")
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
342
It is not an Armstrong number
Program Code:
In this example, we will use the while loop for printing the multiplication table of a given
number. The code is given below -
1. num = 21
2. counter = 1
3. # we will use a while loop for iterating 10 times for the multiplication table
4. print("The Multiplication Table of: ", num)
5. while counter <= 10: # specifying the condition
6. ans = num * counter
7. print (num, 'x', counter, '=', ans)
8. counter += 1 # expression to increment the counter
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Now we give code examples of while loops in Python for square every number of a list.
The code is given below -
7. squares.append( (list_.pop())**2)
8. # Print the squares of all numbers.
9. print( squares )
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
In the preceding example, we execute a while loop over a given list of integers that will
repeatedly run if an element in the list is found.
Program Code 2:
Now we give code examples of while loops in Python for determine odd and even number
from every number of a list. The code is given below -
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
It is an odd number
It is an even number
It is an even number
It is an even number
It is an even number
It is an odd number
It is an odd number
It is an even number
Program Code 3:
Now we give code examples of while loops in Python for determine the number letters of
every word from the given list. The code is given below -
1. List_= ['Priya', 'Neha', 'Cow', 'To']
2. index = 0
3. while index < len(List_):
4. element = List_[index]
5. print(len(element))
6. index += 1
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
5
4
3
2
We can construct a while loop with multiple conditions in this example. We have given
two conditions and a and keyword, meaning the Loop will execute the statements until
both conditions give Boolean True.
Program Code:
Now we give code examples of while loops in Python for multiple condition. The code is
given below -
1. num1 = 17
2. num2 = -12
3.
4. while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop
5. num1 -= 2
6. num2 += 3
7. print( (num1, num2) )
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
(15, -9)
(13, -6)
(11, -3)
Code
1. num1 = 17
2. num2 = -12
3.
4. while num1 > 5 or num2 < -5 :
5. num1 -= 2
6. num2 += 3
7. print( (num1, num2) )
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
(15, -9)
(13, -6)
(11, -3)
(9, 0)
(7, 3)
(5, 6)
We can also group multiple logical expressions in the while loop, as shown in this example.
Code
1. num1 = 9
2. num = 14
3. maximum_value = 4
4. counter = 0
5. while (counter < num1 or counter < num2) and not counter >= maximum_value: # grou
ping multiple conditions
6. print(f"Number of iterations: {counter}")
7. counter += 1
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Number of iterations: 0
Number of iterations: 1
Number of iterations: 2
Number of iterations: 3
Continue Statement
It returns the control of the Python interpreter to the beginning of the loop.
Code
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Output:
Current Letter: W
Current Letter: h
Current Letter: l
Current Letter:
Current Letter: L
Current Letter: p
Current Letter: s
Break Statement
It stops the execution of the loop when the break statement is reached.
Code
Output:
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for
classes, functions, and empty control statements.
Code
Now we compile the above code in python, and after successful compilation, we run it.
Then the output is given below -
Output:
The break is commonly used in the cases where we need to break the loop for a given
condition. The syntax of the break statement in Python is given below.
Syntax:
1. #loop statements
2. break;
Output:
Item matched
Found at location 2
In the above example, a list is iterated using a for loop. When the item is matched with
value 4, the break statement is executed, and the loop terminates. Then the count is
printed by locating the item.
Example 2 : Breaking out of a loop early
Code
Output:
p
y
t
h
When the character is found in the list of characters, break starts executing, and iterating
stops immediately. Then the next line of the print statement is printed.
Output:
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.