Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

Python:Loops

1.how to remove specific char from string
how to remove vowels from string
2.How to iterate or display the each value of number where data type is number using for loop
3.How to iterate the each value of number where data type is number using for loop
4.How to print the each letter of string with if-else statements using for loop
5.How to print even and odd no in tuples
6.How to iterate through a sequence of items using range() method in list data type using for loop
7.How to display the each value of tuple using indexing function for loop(for iterator in range(len(tuple_)))
8.Apply for loop in key value pair

for string in "Python Loops":  
    if string == "o" or string == "p" or string == "t":
Enter fullscreen mode Exit fullscreen mode

how to remove specific char from string
how to remove vowels from string

original_string = "Python Loops"
characters_to_remove = ["o", "p", "t"]
removed_characters = []

for char in original_string:
    if char in characters_to_remove:
        original_string = original_string.replace(char, "")
        removed_characters.append(char)
Enter fullscreen mode Exit fullscreen mode

how to remove specific char from string where specific char stored in list
declare a original string, list contain a char to remove
declare empty list for print matched char
declare empty string to print char after removing char from original string
apply for loop in original string
if char of original string not in list that contain a char to remove, then add that string in empty string otherwise append that char in empty list

original_string = "Python Loops"
characters_to_remove = ["o", "p", "t"]
removed_characters = []

new_string = ""

for char in original_string:
    if char not in characters_to_remove:
        new_string += char
    else:
        removed_characters.append(char)

print("Original String:", original_string)
print("New String after removing characters:", new_string)
print("Removed Characters:", removed_characters)
Enter fullscreen mode Exit fullscreen mode

how to remove vowels from string where vowels stored in string

data = "python"
vowels = "aeiou"
mynew = ""

for char in data:
    if char not in vowels:
        mynew += char

print("Original String:", data)
print("String after removing vowels:", mynew) 
Enter fullscreen mode Exit fullscreen mode
mydata="programing"
vowel="aeiouAEIOU"
data=[data for data in mydata if data not in vowel]
char=""
for datas in data: 
    char += datas
print(char)
Enter fullscreen mode Exit fullscreen mode

output 

prgrmng
Enter fullscreen mode Exit fullscreen mode

Using above logic we can remove vowel from string

display a prime no in number data type using for loop
display a multiplication number data type using for loop

for Loop
Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is known as iteration.

Syntax of the for Loop

for value in sequence:

 { code block } 
Enter fullscreen mode Exit fullscreen mode

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
Python program to show how the for loop works

Creating a sequence which is a tuple of numbers

numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]

*variable to store the square of the number *
square = 0

Creating an empty list

squares = []

Creating a for loop

for value in numbers:  
    square = value ** 2  
    squares.append(square)  
print("The list of squares is", squares) 
Enter fullscreen mode Exit fullscreen mode

Output:

The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1, 81, 4]
Enter fullscreen mode Exit fullscreen mode

Using else Statement with for Loop
As already said, a for loop executes the code block until the sequence element is reached. The statement is written right after the for loop is executed after the execution of the for loop is complete.

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.

Here is a code to better understand if-else statements.

Code

P*ython program to show how if-else statements work*

string = "Python Loop"

# Initiating a loop  
for s in a string:  
    # giving a condition in if block  
    if s == "o":  
        print("If block")  
    # if condition is not satisfied then else block will be executed  
    else:  
        print(s) 
Enter fullscreen mode Exit fullscreen mode

Output:

P
y
t
h
If block
n

L
If block
If block
p
Enter fullscreen mode Exit fullscreen mode

Python program to show how to use else statement with for loop

# Creating a sequence  
tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)  

# Initiating the loop  
for value in tuple_:  
    if value % 2 != 0:  
        print(value)  
# giving an else statement  
else:  
    print("These are the odd numbers present in the tuple")  
Enter fullscreen mode Exit fullscreen mode

Output:

3
9
3
9
7
These are the odd numbers present in the tuple
Enter fullscreen mode Exit fullscreen mode

The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce values between 0 and 9. (10 numbers).

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.

The example that follows will make this clear.

Code

Python program to show the working of range() function

print(range(15))  

print(list(range(15)))  

print(list(range(4, 9)))  

print(list(range(5, 25, 4)))  
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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

Python program to iterate over a sequence with the help of indexing

tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")  

# iterating over tuple_ using range() function  
for iterator in range(len(tuple_)):  
    print(tuple_[iterator].upper())  
Enter fullscreen mode Exit fullscreen mode

Output:

PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE
Enter fullscreen mode Exit fullscreen mode

Using else Statement with while Loops
As discussed earlier in the for loop section, we can use the else statement with the while loop also. It has the same syntax.

Code

Python program to show how to use else statement with the while loop

counter = 0

 Iterating through the while loop  
while (counter < 10):      
    counter = counter + 3  
    print("Python Loops") # Executed untile condition is met  
 Once the condition of while loop gives False this statement will be executed  
else:  
    print("Code block inside the else statement") 
Enter fullscreen mode Exit fullscreen mode

Output:

Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement
Enter fullscreen mode Exit fullscreen mode

Continue Statement
It returns the control to the beginning of the loop.

Code

Python program to show how the continue statement works

Initiating the loop

for string in "Python Loops":  
    if string == "o" or string == "p" or string == "t":  
         continue  
    print('Current Letter:', string)  
Enter fullscreen mode Exit fullscreen mode

Output:

Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:  
Current Letter: L
Current Letter: s
Enter fullscreen mode Exit fullscreen mode

Break Statement
It stops the execution of the loop when the break statement is reached.

Code

Python program to show how the break statement works

Initiating the loop

for string in "Python Loops":  
    if string == 'L':  
         break  
    print('Current Letter: ', string) 
Enter fullscreen mode Exit fullscreen mode

Output:

Current Letter:  P
Current Letter:  y
Current Letter:  t
Current Letter:  h
Current Letter:  o
Current Letter:  n
Current Letter:
Enter fullscreen mode Exit fullscreen mode

Pass Statement
Pass statements are used to create empty loops. Pass statement is also employed for classes, functions, and empty control statements.

Code

Python program to show how the pass statement works

for a string in "Python Loops":  
    pass  
print( 'Last Letter:', string) 
Enter fullscreen mode Exit fullscreen mode

Output:

Last Letter: s
Enter fullscreen mode Exit fullscreen mode

Python While Loop Example
Here we will sum of squares of the first 15 natural numbers using a while loop.

Code

Python program example to show the use of while loop

num = 15

 initializing summation and a counter for iteration  
summation = 0  
c = 1  

while c <= num: # specifying the condition of the loop  
    # begining the code block  
    summation = c**2 + summation  
    c = c + 1    # incrementing the counter 



 print the final sum  
print("The sum of squares is", summation)  
Enter fullscreen mode Exit fullscreen mode

Output:

The sum of squares is 1240
Enter fullscreen mode Exit fullscreen mode

Prime Numbers and Python While Loop
Using a while loop, we will construct a Python program to verify if the given integer is a prime number or not.

Code

num = [34, 12, 54, 23, 75, 34, 11]    

def prime_number(number):  
    condition = 0  
    iteration = 2  
    while iteration <= number / 2:  
        if number % iteration == 0:  
            condition = 1  
            break  
        iteration = iteration + 1  

    if condition == 0:  
        print(f"{number} is a PRIME number")  
    else:  
        print(f"{number} is not a PRIME number")  
for i in num:  
    prime_number(i) 
Enter fullscreen mode Exit fullscreen mode

Output:

34 is not a PRIME number
12 is not a PRIME number
54 is not a PRIME number
23 is a PRIME number
75 is not a PRIME number
34 is not a PRIME number
11 is a PRIME number
Enter fullscreen mode Exit fullscreen mode

Multiplication Table using While Loop
In this example, we will use the while loop for printing the multiplication table of a given number.

Code

num = 21        
counter = 1      
 we will use a while loop for iterating 10 times for the multiplication table        
print("The Multiplication Table of: ", num)      
while counter <= 10: # specifying the condition  
    ans = num * counter      
    print (num, 'x', counter, '=', ans)      
    counter += 1 # expression to increment the counter  
Enter fullscreen mode Exit fullscreen mode

Output:

The Multiplication Table of:  21
21 x 1 = 21
21 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210
Enter fullscreen mode Exit fullscreen mode

Python While Loop with List
We will use a Python while loop to square every number of a list

Code

Python program to square every number of a list

 initializing a list  
list_ = [3, 5, 1, 4, 6]  
squares = []  
 programing a while loop   
while list_: # until list is not empty this expression will give boolean True after that False  
    squares.append( (list_.pop())**2)  
 print the squares  
print( squares )  
[36, 16, 1, 25, 9]
Enter fullscreen mode Exit fullscreen mode

Python While Loop Multiple Conditions
We'll need to recruit logical operators to combine two or more expressions specifying conditions into a single while loop. This instructs Python on collectively analyzing all of the given expressions of conditions.

We can construct a while loop with multiple conditions in this example. We have given two conditions and a and keyword, meaning until both conditions give boolean True, the loop will execute the statements.

Code

num1 = 17  
num2 = -12  

while num1 > 5 and num2 < -5 : # multiple conditions in a single while loop  
    num1 -= 2  
    num2 += 3  
    print( (num1, num2) )  
Enter fullscreen mode Exit fullscreen mode

Output:

(15, -9)
(13, -6)
(11, -3)
Enter fullscreen mode Exit fullscreen mode

We can also group multiple logical expressions in the while loop, as shown in this example.

Code

num1 = 9   
num = 14   
maximum_value = 4  
counter = 0   
while (counter < num1 or counter < num2) and not counter >= maximum_value: # grouping multiple conditions  
    print(f"Number of iterations: {counter}")   
    counter += 1  
Enter fullscreen mode Exit fullscreen mode

Output:

Number of iterations: 0
Number of iterations: 1
Number of iterations: 2
Number of iterations: 3
Enter fullscreen mode Exit fullscreen mode

Example 3

n=2  
while 1:  
    i=1;  
    while i<=10:  
        print("%d X %d = %d\n"%(n,i,n*i));  
        i = i+1;  
    choice = int(input("Do you want to continue printing the table, press 0 for no?"))  
    if choice == 0:  
        break;      
    n=n+1  
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Do you want to continue printing the table, press 0 for no?0

Code

Python code to show example of continue statement

looping from 10 to 20  
for iterator in range(10, 21):  

    If iterator is equals to 15, loop will continue to the next iteration  
    if iterator == 15:  
        continue  
    otherwise printing the value of iterator  
    print( iterator ) 
Enter fullscreen mode Exit fullscreen mode

Output:

10
11
12
13
14
16
17
18
19
20
Enter fullscreen mode Exit fullscreen mode

Apply for loop in key value pair

# Example dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Iterate over dictionary items using a for loop
for key, value in my_dict.items():
    print(f'Key: {key}, Value: {value}')
Enter fullscreen mode Exit fullscreen mode

Output

Key: key1, Value: value1
Key: key2, Value: value2
Key: key3, Value: value3
Enter fullscreen mode Exit fullscreen mode

Image description

how to check even or odd on given tuple

data = (4, 6, 9, 10)
my_list = []

for number in data:
    if number % 2 == 0:
        my_list.append(number)
print("Original String:", my_list)
for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

how to check even or odd 1 to 10

my_list = []

for number in range(1,10):
    if number % 2 == 0:
        my_list.append(number)
print("Original String:", my_list)
for item in my_list:
    print("Original String:", item)
Enter fullscreen mode Exit fullscreen mode

how to check even or odd on given tuple using range method

data = (4, 6, 9, 10)
my_list = []

for index in range(len(data)):
    if data[index] % 2 == 0:
        my_list.append(data[index])

print("Original List of Even Numbers:", my_list)

for item in my_list:
    print("Even Number:", item)
Enter fullscreen mode Exit fullscreen mode

Some More Examples

Image description

Image description

Image description

Image description

Image description

Image description

Top comments (0)