Python - For Loops

For loops are by far the easiest and most efficient looping technique in Python. For loops allow us to iterate over a variable 'x' any number of times, usually specified in a range or len function.

>>> x = int(24/6)
>>> y = int(8/2)
>>> for i in range(10):
...   if x != y:
...     print(x + y)
>>>

Why does the above code block not print the value of x plus y?

We can also use a for-loop and range for our Fibonacci sequence. At the prompt...

>>> def fib(n):
...       a, b = 0, 1
...       for i in range(n-1):
...         a, b = b, a + b
...         print(a)
...
>>> fib(25)
1  
1  
2  
3  
5  
8  
13  
21  
34  
55  
89  
144  
233  
377  
610  
987  
1597  
2584  
4181  
6765  
10946  
17711  
28657  
46368  

Great. But what about database record iteration?

Looping for databases

For loops are useful when working with database records. From inserting records, updating records, or deleting records, for loops are essential to web and database development. Deelopers are constantly iterating over a sets of records and sending that output to the browser or back into the database for other operations.

My example uses pymongo to insert names into a collection in MongoDB.

customer_names.py

import pymongo

# database connection
connection = pymongo.MongoClient('localhost', 27017)  
db = connection.names

# define our data structure, essentially a python dict()
cd = {}  
cd["_id"] = "BC1234"  
cd["Address Info"] = "1234 Main Street"  
cd["Contact Info"] = "555-111-1212"  
cd["Order Info"] = "Order ID: 1647785"  
cd["Membership Status"] = "Active"  
'''  
If we were to print this out at the console, it would look like this  
print(cd)  
{'_id' : 'BC1234', 'Address Info' : '1234 Main Street', 'Contact Info' : '555-111-1212', 'Order Info' : 'Order ID: 1647785', 'Membership Status' : 'Active'}
'''  
# now back to what we were doing, the for-loop for a database insert
# iterate over the keys and values and insert into our database
for item in cd['data']['children']:  
  db.names.insert_one(item['data'])

We'll be doing much more For loops in coming app building sections.

Practice for loops in the Python console.

Craig Derington

Veteran full stack web dev focused on deploying high-performance, responsive, modern web applications using Python, NodeJS, Django, Flask, MongoDB and MySQL.

comments powered by Disqus