Python for Loop With Examples

Daftar Isi: (toc)

In Python programming language there are two loops for..in loop and while loop. In this tutorial you’ll learn about for loop in Python is used to iterate over a sequence (like string, list, tuple).


Syntax of Python for loop


for var in sequence:
for loop body
else:
else_suite

All the elements in the sequence are iterated one by one using the for loop, in each iteration element is assigned to the “var” and the for loop body is executed.

The for loop in Python also includes an optional else clause.

for loop flow

Python for Loop

Python for loop examples

1- If you want to display characters of a String using for loop in Python.


str = 'Test'
for ch in str:
print(ch)

Output


T
e
s
t

2- Display all the elements in a list using for loop in Python.


cities = ['New York', 'London', 'Mumbai', 'Paris', 'Madrid']
for city in cities:
print(city)

Output


New York
London
Mumbai
Paris
Madrid

for loop with range sequence type

The range type represents an immutable sequence of numbers and is commonly used for looping a specific number of times in for loops.

Syntax of range is-


range([start,] stop[, step])

If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0.

1- Iterating 0..9 using range and for loop.


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

Output


0
1
2
3
4
5
6
7
8
9

Since start and step arguments are omitted in the range so by default step is 1 and start is 0.

2- Display odd numbers between 1 and 10 using range and for loop in Python.


for i in range(1, 10, 2):
print(i)

Output


1
3
5
7
9

Here start argument is 1 and step is 2.

3- To display all the elements in a list using index.

Using len function you can get the total number of elements in the list which becomes an argument for range.


cities = ['New York', 'London', 'Mumbai', 'Paris', 'Madrid']
for i in range(len(cities)):
print(cities[i])

Output


New York
London
Mumbai
Paris
Madrid

Python for loop with else statement

In Python for loop has an optional else statement too. If the for loop runs till completion and terminates the else-suite is executed.

If for loop doesn’t run completely because of any of the following reason, else statement is not executed.

  • for loop is terminated abruptly due to a break statement
  • for loop is terminated abruptly due to a return statement
  • if an exception is raised

Here is an example showing a scenario where for loop with else statement can come handy. If you want to implement a functionality to find an element in array. If element is found in the array then its index is returned otherwise -1 is returned.

In this scenario you can use else statement with python for loop. If an element is found you will return its index so else suite won’t be executed. If for loop runs till completion that would mean searched element is not found in the array in that case else suite is executed and -1 is returned.


from array import *
def find_in_array(array, value):
for index, e in enumerate(array):
if e == value:
return index
# else associated with for loop
else:
return -1

a = array('i', [3,4,5,6,7])
find_value = 4
index = find_in_array(a, find_value)
if index != -1:
print(find_value, 'found in array at index', index)
else:
print(find_value, 'not found in array')

Output


4 found in array at index 1

Nested for loop

for loop can be nested which means you can have one for loop inside another. In the nested loops for each iteration of the outer for loop, inner for loop is iterated for the given range of elements.

Python Nested for loop example

In the example a pyramid pattern using * is displayed using nested for loops.


rows = 6
for i in range (1, rows):
for j in range (0, rows -i):
#print spaces, end='' ensures control
# remains on the same line
print(' ', end='')
for k in range (0, i):
print('* ', end='')
print()

Output


*
* *
* * *
* * * *
* * * * *

Though in Python same pyramid pattern can be displayed very elegantly using a single for loop.


rows = 6
for i in range (1, rows):
#repeat space for given times
print(' '*rows, end='')
print('* '*(i))
rows = rows -1

That's all for this topic Python for Loop With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python Conditional Statement - if, elif, else Statements
  2. Python return Statement With Examples
  3. Python break Statement With Examples
  4. Method Overriding in Python
  5. Name Mangling in Python

You may also like-

  1. Passing Object of The Class as Parameter in Python
  2. Nonlocal Keyword in Python With Examples
  3. String Slicing in Python
  4. Python Exception Handling Tutorial
  5. Association, Aggregation And Composition in Java
  6. Why Class Name And File Name Should be Same in Java
  7. Just In Time Compiler (JIT) in Java
  8. BeanFactoryPostProcessor in Spring Framework
Find Out
Related Post



Ikuti AltairGate.com pada Aplikasi GOOGLE NEWS : FOLLOW (Dapatkan Berita Terupdate tentang Dunia Pendidikan dan Hiburan). Klik tanda  (bintang) pada aplikasi GOOGLE NEWS.

Disclaimer:
Kebijakan Hak Cipta:

Semua Gambar, artikel ataupun video yang di publikasikan situs ini terkadang berasal dari berbagai sumber media lain, tidak terkait dengan kami sama sekali yang artinya milik penulisnya masing-masing. Kami hanya menyediakan wallpaper gratis yang menarik dari seluruh internet.

Semua kredit dan terima kasih ditujukan kepada penulis, pemilik dan pengunggah asli. Kami menghormati Hukum Hak Cipta. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. penggunaan komersial apa pun sangat dilarang tanpa persetujuan sebelumnya dari penulis.

Kami Berkomitmen untuk menghapus foto atau wallpaper yang melanggar hak cipta dari blog kami.

Jika Anda menemukan konten yang tidak perlu di sini, silakan hubungi (radhyantz@gmail.com) sesegera mungkin sehingga kami dapat melakukan sesuatu tentang hal itu.

Seperti menghapusnya atau meletakkan nama Anda di bawahnya. Setiap foto yang ada di situs dapat dihapus atas permintaan sederhana dari penulis. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini. Terima kasih..

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.