banner



How To Print 1 To 10 In Python Using For Loop

for Loop In Python - Complete Guide


In this tutorial, nosotros are going to learn about for loop in Python. We will see how to utilise information technology in different ways, iteration over numbers, list, dictionary, tuple, cord, range, set, file, etc with multiple examples. Nosotros volition as well run across the nesting of loops and how to apply a break and continue keywords in for loop.

    Table of Contents

  1. What is loop in Python
  2. for Loop
    • for loop syntax
    • Iteration over numbers
  3. For loop with alphabetize
  4. Interruption loop
  5. Go along loop
  6. Nested loop
  7. Loop with else

What is loop in Python?

A loop in python is a sequence of statements that are used to execute a cake of code for a specific number of times.

You can imagine a loop as a tool that repeats a task multiple times and stops when the task is completed (a status satisfies).

A loop in Python is used to iterate over a sequence (listing, tuple, cord, etc.)

In that location are unlike types of loops in Python. They are:

  • For loop
  • While loop
  • Do while loop

Let's run across what is a for loop, how to use it, and everything else you demand to know.


Python for Loop

A for loop most unremarkably used loop in Python. It is used to iterate over a sequence (list, tuple, string, etc.)

Notation: The for loop in Python does not work like C, C++, or Java. It is a bit different.

for loop in python

Python for loop is not a loop that executes a cake of code for a specified number of times. It is a loop that executes a block of code for each chemical element in a sequence.

It means that you can't define an iterator and iterate over increasing or decreasing values like in C.

for Loop Syntax In Python

Use for keyword to ascertain for loop and the iterator is divers using in the keyword.

The iterator is the variable that is used to iterate over the sequence. Information technology is used to access each element in the sequence.

The for loop in Python is defined using the following syntax:

          for iterator_variable in sequence:   # loop torso   # ...        

# Flowchart

python for loop flowchart

If you accept any sequence of values, you lot tin use for loop to iterate over it.

# Example 1: Looping list

          # Using for loop on listing fruits = ['orangish', 'apple', 'pear', 'banana', 'kiwi']  # Using for loop # loop will run the code for each item in the listing for fruit in fruits:     print(fruit)        

Output:

orange apple tree pear banana kiwi

# Example 2: Looping tuple

A tuple is also a sequence of values but like a listing. It is immutable and enclosed in parentheses instead of foursquare brackets.

          # looping over tuples items = ('one', 'two', 'three') for item in items:     impress(particular)        

Output:

# Example iii: Looping cord

A cord is also a sequence of values just like a listing. It is immutable and enclosed in double quotes instead of square brackets.

          # looping over string items = 'looping' for item in items:     print(item)        

Output:


Looping a range of number

You take learned above that for loop in python does not iterate between 2 numbers just over a sequence of items.

So how tin can we loop over a range of numbers?💭🤔

💡 Simply by creating a sequence of numbers and using the range() function.

range() is a built-in function in Python that creates a sequence of numbers and is used to iterate over a sequence of numbers.

In the for loop, yous can replace the sequence with the range() function.

# Instance four: Looping numbers

          # looping start 5 numbers for i in range(5):     impress(i)        

Output:

Y'all can meet that the range() function creates a sequence of numbers from 0 to 4. The number five is not included in the sequence.

To loop between a given range of numbers m and n you lot can use range(m, north) (where due north is non included). To include n you tin can use range(m, n+1).

# Example 5: Looping between a range of number

          # looping betwixt a range of numbers  # looping from v to 10 for i in range(5, 10): # 10 non included     impress(i, terminate=' ') print()  # looping 20 to 30 (thirty included) for i in range(20, 31):     print(i, end=' ')        

Output:

5 6 vii 8 ix xx 21 22 23 24 25 26 27 28 29 30

The range() function has a default increase of 1. You tin change the increment by passing your own step as the third argument.

Annotation: The steps can just exist integers either positive or negative. Decimals are non allowed.

# Example half-dozen: Looping with step

          # looping with step  # jumping past 2 for i in range(0, 10, 2):     print(i, stop=' ') print()  # jumping by 3 for i in range(0, 10, 3):     print(i, end=' ') print()  # negative step for i in range(10, 0, -2):     print(i, stop=' ') print()        

Output:

0 ii 4 6 eight 0 3 vi 9 10 7 4 1

Python For loop with index

As you lot know that python for loop iterates over a sequence of values. Only what if yous want to access the index of the value in the sequence?🤔

Yous can access the index of the value in the sequence past using the length of the sequence in loop range function and accessing element in the sequence using an index.

# Example 7: Looping with index

          # looping with index fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi'] for i in range(len(fruits)):     print(i, fruits[i])        

Output:

0 orangish one apple 2 pear three banana 4 kiwi

# Alternate way to get the index

In Python, you lot can use the enumerate() office to go the alphabetize of the value in the sequence.

enumerate() is a born function in Python that returns an enumerated object. This object can be used to loop over the sequence and get the alphabetize of the value.

# Example 8: Enumerate

          # looping with index  fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi'] for i, fruit in enumerate(fruits):     print(i, fruit)        

Output:

0 orangish one apple two pear 3 banana 4 kiwi

Ezoic

Python break for loop

There are situations when you lot want the loop to stop when a status is met. Similar in a sum of numbers, you want to end when the sum is greater than 100.

To do this y'all can utilise the interruption keyword with if statement to cease and exit the loop. The pause is a keyword in Python which is used to get out the loop.

# Example nine: Breaking a loop

          # breaking a loop  # break loop when i == 5 for i in range(10):     if i == five:         break     print(i, end=' ') print()  # pause loop when sum is greater than 100 sum = 0 for i in range(10):     sum += i * 1     if sum > 100:         pause impress("Sum = ", sum)        

Output:


go on for loop python

Simply similar breaking a loop, you tin can too proceed the loop. Standing loop ways skipping the current iteration and continuing with the next iteration.

To practice this y'all can use the go on keyword to skip the current iteration and continue with the next iteration.

This is helpful when you want to include some specific item from the sequence.

# Example 10: Continuing a loop

          # standing a loop  # continue loop when i == five or i == 7 for i in range(10):     if i == 5 or i == 7:         continue     print(i, cease=' ') print()        

Output:

Adding all fifty-fifty numbers from a list of numbers.

# Example 11: Calculation evens

          # adding evens    numbers = [five, 12, eight, ix, x, eleven, 13, 14, 15] sum = 0 for i in numbers:     if i % 2 != 0:         continue     sum += i print("Sum = ", sum)        

Output:


Nested for loop python

Yous tin also nest for loops. A nesting loop means to loop over a sequence of sequences.

This is useful when yous want to loop over a sequence of items and and so loop over the items in that sequence (loop inside the loop).

We volition use a nested loop in creating design programs in python.

# Example 12: Nested for loop

          # nested for loop size = 5  for i in range(ane, size+1):     # nested loop     for j in range(one, i+1):         impress("*", cease="")     print()        

Output:


for loop with else

You can also use else keyword in python for loop. This is useful when y'all want to execute some code when the loop is finished.

The else cake is executed when the loop is finished.

# Example xiii: for loop with else

          # for loop with else for i in range(3):     print(i) else:     impress("Loop Finished")        

Output:

When there is a break statement in the loop, the else block is not executed.

The else block with interruption argument is only executed when the break argument is itself non executed. i.due east the status for the break statement is not met.

# Example 15

          # for loop with else and break  # else not executed with interruption statement for i in range(3):     if i == 2:         pause     impress(i) else:     print("Loop Finished") print()  # else executed with break statement for i in range(three):     if i == v:         break     impress(i) else:     impress("Loop Finished")        

Output:


Conclusions

We accept covered everything that yous demand to know nearly for loop in python. You tin can use for loop to iterate over a sequence of items and start writing your own program.

To practice for loop, y'all can create offset patterns, alphabet patterns, and number patterns in python.

Frequently Asked Questions

  1. How practise you repeat a lawmaking in Python?

    You can use for loop to repeat a code.

  2. How do you write a for loop?

    You can utilise for keyword to write a for loop. Example:

                    for iterator_variable in sequence:   # loop body   # ...              

How To Print 1 To 10 In Python Using For Loop,

Source: https://www.tutorialstonight.com/python/for-loop-in-python.php

Posted by: brannsonsise.blogspot.com

0 Response to "How To Print 1 To 10 In Python Using For Loop"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel