Sunday, April 20, 2025

Python For Loops

For loops are awesome when we need to repeat same operation - they are great for custom reports, for example:


colors = ("red", "blue", "yellow", "green")

for x in colors:
    print(x)

Result: 


red
blue
yellow
green
>>> 

Even better, explain what you are doing:


colors = ("red", "blue", "yellow", "green")

for x in colors:
    print("Elements is: ", x)

Result:  


Elements is:  red
Elements is:  blue
Elements is:  yellow
Elements is:  green
>>> 

For example, we can check if sites are available, with a little bit of pause between checks.

To pause operations, we will import "time" modul to aktivate sleep() function for 2 seconds.

With system() function from "os" module we can run terminal apps just as we use them in terminal or command prompt on machines with Windows.


import os, time

ip = ["127.0.0.1", "google.com"]

for x in ip:
    os.system("ping " + x)
    time.sleep(2)

Now when we know about For Loops, understanding Dictionary Iterations will be easy.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...