Sitemap
GIS-ish

GIS-ish

Learning python for spatial data analysis

Python — For loop

2 min readAug 30, 2022
Press enter or click to view image in full size
Photo by James Harrison on Unsplash

Using a loop we can perform calculations on each item. Since bulk processing is the main goal of python repeating processes on loops is constantly needed. Now let’s look through the loop.

The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.

Cities = ['Bombay','Delhi','Calcutta','Pune','Kochi','Ahmedabad']States = ['Karnataka', 'Delhi', 'West Bengal','Maharashtra','Kerala', 'Gujarat']

States = [‘Karnataka’, ‘Delhi’, ‘West Bengal’,’Maharashtra’,’Kerala’, ‘Gujarat’]

  • Syntax of “for loop”

- x is the variable used in the syntax, it can be any name or letter you like.

- The statement of the for loop must end with a :

- To end any loop just change the indentation to normal

for x in Cities:
print(x)
Bombay
Delhi
Calcutta
Pune
Kochi
Ahmedabad
  • range() function

To perform an iteration over a sequence of whole numbers we use range() function.

In simple form range(4) function prints number from 0–3.

Get GIS-ish’s stories in your inbox

Join Medium for free to get updates from this writer.

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

for no in range(4):
print(no)
print("/")
for no in range(1,6,2):
print(no)
0
1
2
3
/
1
3
5
  • Iterate over a list using indexing

range() function can be combined with the len() function to iterate through a sequence using indexing.

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.

for i in range(len(Cities)):
print(f"Metro cities of India: {i+1} - {Cities[i]}")
else:
print("No items left")
Metro cities of India: 1 - Bombay
Metro cities of India: 2 - Delhi
Metro cities of India: 3 - Calcutta
Metro cities of India: 4 - Pune
Metro cities of India: 5 - Kochi
Metro cities of India: 6 - Ahmedabad
No items left

The body of a loop can contain many statements

sum = 0for i in range(10):
sum = sum+i
mean = sum/len(range(10))
print(f'The sum is {sum}. And mean is {mean}')
The sum is 45. And mean is 4.5

break

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

for no in range(4):
print(no)
break
0

For more information, please have a look at the sites linked below.

--

--

GIS-ish
GIS-ish

Written by GIS-ish

Learning python for spatial data analysis