Skip to content
Home » 10 Ways to Use Python For Loop, What is For Loop in Python?

10 Ways to Use Python For Loop, What is For Loop in Python?

  • by
10 Ways to use Python For Loop

Python for loop is commonly used in data science to loop through an iterable object (such as a list, tuple, set, etc.) and execute the same operation for each entry.

A for loop, for example, allows us to cycle thru a list of items, performing the identical action on each one.

10 Ways to use Python For Loop

(By the way, an iterable object would be any Python item that we can iterate over, or “loop,” and return a single element at a time.) Iterable lists, for example, return a single list item at a time, in the order in which the entries are listed.

Iterable strings yield one line at a time, in the order in which the characters appear, and so on.)

A for loop is made by first specifying the iterable object you want to loop through, and then specifying the actions you want to perform on each item in that iterable object.

Use a list

In this instance, we’ll use the for loop to traverse through the list’s individual values. We create a variable named number and set it to a list of integers ranging from 1 to 5. Next, cycle through this list and determine the square of num by multiplying it by itself inside the loop. 10+ real-life looping examples in Python This script’s output is as follows:

# python3 for-loop-2.py

squared is 1

squared is 4

squared is 9

squared is 16

squared is 25

Use string

We’ll utilize a string with a for loop in this example. Now, in our last example, we utilized a “list” with some values, and we used a for loop to traverse through the list’s individual elements.

String for loop, on the other hand, iterates through each individual character. We’ll write a Python script that takes user input for a string and then iterates over the characters in that string using a for a loop.

p --- 0

y --- 1

t --- 2

h --- 3

o --- 4

n --- 5

Use a dictionary

There are several methods for looping with a dictionary now. I’ve covered a variety of circumstances and approaches for printing key, value, or key in one single script: value pair from a python dictionary paired with a for loop:

~]# python3 for-loop-4.py

----- Scenario-1-----

KEY: a

KEY: b

KEY: c

----- Scenario-2-----

KEY: a

KEY: b

KEY: c

----- Scenario-3-----

VALUE: 1

VALUE: 2

VALUE: 3

Use else statement

An else statement can be used with a for loop in the same way that a while statement can. Here’s an example of a list having some integers in it. To cycle through this list and see if particular numbers are included, we’ll use a for a loop.

anitem = 'Hello WholeBlogs'
for item in anitem:
	pass
else:
	print(item)

Ways to use Python For Loop

Using the range() method

The range is a built-in function in Python that generates a list of numbers. This list is mainly used with a for loop to iterate over.

This method is used when you want to repeat an action a certain number of times and don’t worry about the index.

For example, if you wish to locate or calculate all even numbers between 0 and 100, Python will list or print out all even values in that range, except 10, which is an even number.

for i in range(0, 10):
	print(i)

using a while for loo

You may iterate over a list (or another iterable) using Python for loop with range while keeping track of the index.

Python’s nested for loop

Nesting is described as the process of nesting loops inside loops. Although nesting loops is frowned upon in some applications, it is occasionally required to get the desired effect. When you need to retrieve data within a complex data structure, nesting loops come in handy.

It could also be the result of comparing two different data structures. A computation that takes values from two lists, for example, would require you to loop through both lists and then execute the result.

We’ll construct a variable named groups in our next example script, which is a list that contains three additional lists of three integers each. We obtain [1,2,3] if we loop over the first list, but we need to add another loop to traverse over this list to get individual integers.

Use the break statement

We’ve already seen an example of using the break statement with the for..else block to exit a loop. You can use the break statement to quit a loop depending on an external trigger.

This means you can leave the loop based on a circumstance that occurs outside of it. This statement is frequently combined with a conditional if statement. Here’s a simple example of the break statement in action:

for num in range(1,6):
	print(num)
	if num == 4:
		break
	print('Outside for loop')

Output
1
Outside for loop
2
Outside for loop
3
Outside for loop
4

using a while for loo

Use the continue statement

The continue statement skips over the point of a loop where an external condition is triggered and instead completes the rest of the loop.

This implies that the loop’s current run will be paused, but the program will return to the top of the loop and resume execution there.

The continue statement, like the break statement, is frequently used with a conditional if statement. if you are still working on python you must read this post it’s very helpful to you 5 Ways to Initialize a Python Array.

for num in range(1, 5):
	if num == 2:
		continue
	print(num)
	print('Outside for loop')

Output

1
Outside for loop
3
Outside for loop
4
Outside for loop

using a while for loo

 

Use the pass statement

You can use the pass statement to handle an external trigger condition without influencing the loop’s execution. This means that until the loop encounters a break or continue statement later in the code, it will continue to run normally.

The pass statement, like the others, is frequently used in conjunction with a conditional if statement. Normally, we add certain jobs for a condition match when we add an if condition, but if you need to match a condition and do nothing, i.e. continue with the rest of the code, we use “pass.”


for num in range(1, 5):
	if num == 2:
		pass
	else:
		print(num)
print('Outside for loop')

Output

1
3
4
Outside for loop

using a while for loo

To list all files and directories

In this example, we’ll write a Python script that asks for user input. The end-user must choose a path that the script will use to print all files and directories.

~]# python3 for-loop-10.py

Enter your directory path: /tmp/dir1

/tmp/dir1/file1 is a file

/tmp/dir1/sub-dir2 is a directory

/tmp/dir1/sub-dir1 is a directory

/tmp/dir1/file2 is a file

This script checks for the directory within the computer using the os and sys modules.

Read More: How to Run While Loop With Table In PHP?

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *