How do you write a for loop in a python script?

What is for loop in Python?

The for loop in Python is used to iterate over a sequence [list, tuple, string] or other iterable objects. Iterating over a sequence is called traversal.

Syntax of for Loop


for val in sequence:
    loop body

Here, val is the variable that takes the value of the item inside the sequence on each iteration.

Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

Flowchart of for Loop

Flowchart of for Loop in Python

Example: Python for Loop

# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum
sum = 0

# iterate over the list
for val in numbers:
    sum = sum+val

print["The sum is", sum]

When you run the program, the output will be:

The sum is 48

The range[] function

We can generate a sequence of numbers using range[] function. range[10] will generate numbers from 0 to 9 [10 numbers].

We can also define the start, stop and step size as range[start, stop,step_size]. step_size defaults to 1 if not provided.

The range object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in, len and __getitem__ operations.

This function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.

To force this function to output all the items, we can use the function list[].

The following example will clarify this.

print[range[10]]

print[list[range[10]]]

print[list[range[2, 8]]]

print[list[range[2, 20, 3]]]

Output

range[0, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7]
[2, 5, 8, 11, 14, 17]

We can use the range[] function in for loops to iterate through a sequence of numbers. It can be combined with the len[] function to iterate through a sequence using indexing. Here is an example.

# Program to iterate through a list using indexing

genre = ['pop', 'rock', 'jazz']

# iterate over the list using index
for i in range[len[genre]]:
    print["I like", genre[i]]

Output

I like pop
I like rock
​I like jazz

for loop with else

A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts.

The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

Hence, a for loop's else part runs if no break occurs.

Here is an example to illustrate this.

digits = [0, 1, 5]

for i in digits:
    print[i]
else:
    print["No items left."]

When you run the program, the output will be:

0
1
5
No items left.

Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints No items left.

This for...else statement can be used with the break keyword to run the else block only when the break keyword was not executed. Let's take an example:

# program to display student's marks from record
student_name = 'Soyuj'

marks = {'James': 90, 'Jules': 55, 'Arthur': 77}

for student in marks:
    if student == student_name:
        print[marks[student]]
        break
else:
    print['No entry with that name found.']

Output

No entry with that name found.

The for loop in Python is an iterating function. If you have a sequence object like a list, you can use the for loop to iterate over the items contained within the list.

The functionality of the for loop isn’t very different from what you see in multiple other programming languages.

In this article, we’ll explore the Python for loop in detail and learn to iterate over different sequences including lists, tuples, and more. Additionally, we’ll learn to control the flow of the loop using the break and continue statements.

Basic Syntax of the Python for loop

The basic syntax of the for loop in Python looks something similar to the one mentioned below.

for itarator_variable in sequence_name:
	Statements
	. . .
	Statements

Let me explain the syntax of the Python for loop better.

  • The first word of the statement starts with the keyword “for” which signifies the beginning of the for loop.
  • Then we have the iterator variable which iterates over the sequence and can be used within the loop to perform various functions
  • The next is the “in” keyword in Python which tells the iterator variable to loop for elements within the sequence
  • And finally, we have the sequence variable which can either be a list, a tuple, or any other kind of iterator.
  • The statements part of the loop is where you can play around with the iterator variable and perform various function

1. Print individual letters of a string using the for loop

Python string is a sequence of characters. If within any of your programming applications, you need to go over the characters of a string individually, you can use the for loop here.

Here’s how that would work out for you.

word="anaconda"
for letter in word:
	print [letter]

Output:

a
n
a
c
o
n
d
a

The reason why this loop works is because Python considers a “string” as a sequence of characters instead of looking at the string as a whole.

2. Using the for loop to iterate over a Python list or tuple

Lists and Tuples are iterable objects. Let’s look at how we can loop over the elements within these objects now.

words= ["Apple", "Banana", "Car", "Dolphin" ]
for word in words:
	print [word]

Output:

Apple
Banana
Car
Dolphin

Now, let’s move ahead and work on looping over the elements of a tuple here.

nums = [1, 2, 3, 4]

sum_nums = 0

for num in nums:
    sum_nums = sum_nums + num

print[f'Sum of numbers is {sum_nums}']

# Output
# Sum of numbers is 10

3. Nesting Python for loops

When we have a for loop inside another for loop, it’s called a nested for loop. There are multiple applications of a nested for loop.

Consider the list example above. The for loop prints out individual words from the list. But what if we want to print out the individual characters of each of the words within the list instead?

This is where a nested for loop works better. The first loop [parent loop] will go over the words one by one. The second loop [child loop] will loop over the characters of each of the words.

words= ["Apple", "Banana", "Car", "Dolphin" ]
for word in words:
        #This loop is fetching word from the list
        print ["The following lines will print each letters of "+word]
        for letter in word:
                #This loop is fetching letter for the word
                print [letter]
        print[""] #This print is used to print a blank line

Output

4. Python for loop with range[] function

Python range[] is one of the built-in functions. When you want the for loop to run for a specific number of times, or you need to specify a range of objects to print out, the range function works really well. Consider the following example where I want to print the numbers 1, 2, and 3.

for x in range[3]:
    print["Printing:", x]
	
# Output

# Printing: 0
# Printing: 1
# Printing: 2

The range function also takes another parameter apart from the start and the stop. This is the step parameter. It tells the range function how many numbers to skip between each count.

In the below example, I’ve used number 3 as the step and you can see the output numbers are the previous number + 3.

for n in range[1, 10, 3]:
    print["Printing with step:", n]
	
# Output

# Printing with step: 1
# Printing with step: 4
# Printing with step: 7

5. break statement with for loop

The break statement is used to exit the for loop prematurely. It’s used to break the for loop when a specific condition is met.

Let’s say we have a list of numbers and we want to check if a number is present or not. We can iterate over the list of numbers and if the number is found, break out of the loop because we don’t need to keep iterating over the remaining elements.

In this case, we’ll use the Python if else condition along with our for loop.

nums = [1, 2, 3, 4, 5, 6]

n = 2

found = False
for num in nums:
    if n == num:
        found = True
        break

print[f'List contains {n}: {found}']

# Output
# List contains 2: True

6. The continue statement with for loop

We can use continue statements inside a for loop to skip the execution of the for loop body for a specific condition.

Let’s say we have a list of numbers and we want to print the sum of positive numbers. We can use the continue statements to skip the for loop for negative numbers.

nums = [1, 2, -3, 4, -5, 6]

sum_positives = 0

for num in nums:
    if num 

Chủ Đề