Python for loop Example

Filed Under: Python
Python For Loop

Python for loop is used for iterating over a sequence. The for loop is present in almost all programming languages.

Python for loop

We can use for loop to iterate over a list, tuple or strings. The syntax of for loop is:

for itarator_variable in sequence_name:
	Statements
	. . .
	Statements

Let’s look at some examples of using for loop in Python programs.

Using for loop to print each letter of a string

Python string is a sequence of characters. We can use for loop to iterate over the characters and print it.

word="anaconda"
for letter in word:
	print (letter)

Output:

a
n
a
c
o
n
d
a

Iterating over a List, Tuple

List and Tuple are iterable objects. We can use for loop to iterate over their elements.

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

Output:

Apple
Banana
Car
Dolphin

Let’s look at an example to find the sum of numbers in a tuple.

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

Python Nested For Loop

When we have a for loop inside another for loop, it’s called nested for loop. The following code shows nested for loops in Python.

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

python nested for loop example

Python for loop with range() function

Python range() is one of the built-in functions. It is used with for loop to run a block of code specific number of times.

for x in range(3):
    print("Printing:", x)
	
# Output

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

We can also specify start, stop, and step parameters for range function.

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

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.

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

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 < 0:
        continue
    sum_positives += num

print(f'Sum of Positive Numbers: {sum_positives}')

Python for loop with optional else block

We can use else clause with for loop in Python. The else block is executed only when the for loop is not terminated by a break statement.

Let’s say we have a function to print the sum of numbers if and only if all the numbers are even. We can use break statement to terminate the for loop if an odd number is present. We can print the sum in the else part so that it gets printed only when the for loop is executed normally.

def print_sum_even_nums(even_nums):
    total = 0

    for x in even_nums:
        if x % 2 != 0:
            break

        total += x
    else:
        print("For loop executed normally")
        print(f'Sum of numbers {total}')


# this will print the sum
print_sum_even_nums([2, 4, 6, 8])

# this won't print the sum because of an odd number in the sequence
print_sum_even_nums([2, 4, 5, 8])

# Output

# For loop executed normally
# Sum of numbers 20

Conclusion

The for loop in Python is very similar to other programming languages. We can use break and continue statements with for loop to alter the execution. However, in Python, we can have optional else block in for loop too.

Comments

  1. Lee says:

    I keep getting an invalid syntax error when trying to run the code for the Python for use with optional else block. It is saying the inner first bracket is the invalid syntax error- def print_sum_even_nums ([2, 4, 6, 8]):

  2. G N Deepak Sravan says:

    How to use for loop in calculator program in python using functions
    optimized code

  3. Camel says:

    Thanks for this lesson. I’ve learned a lot.

  4. Madhubanti Jash says:

    Hi Pankaj, problem lies with this line “print letter”. It should be print (letter)

    1. Pankaj says:

      Thanks for pointing out the typo error, I have corrected it now. Appreciate it.

  5. Madhubanti Jash says:

    Thank you Imtiaz Abedin for this very useful tutorial series on python.

  6. Saurabh Suthar says:

    Python tutorials are really very helpful. But there are some errors in codes.Like in python nested loop example in print function.

    1. Pankaj says:

      Can you please point out which method is causing the error and what is the error? Could it be because of white spaces in copy paste? White spaces matter a lot in python programming.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages