Sunday, April 20, 2025

Python While Loops

While loops are extremely useful when we need specific lines of code to run constantly.

Basically, we need to define a starting point, ending point, and how to jump from one point to another.

Of course, in between those points, some useful part of code need to be executed:


x = 0

while x < 10:
    print("Value of x atm: ", x)
    x = x + 1

Result: 


Value of x atm:  0
Value of x atm:  1
Value of x atm:  2
Value of x atm:  3
Value of x atm:  4
Value of x atm:  5
Value of x atm:  6
Value of x atm:  7
Value of x atm:  8
Value of x atm:  9
>>> 

We will import os module, so we can run application inside our operating system - using Python script.

"x = x + 1" is used to gradually jump from 0 until 3 is reached - it's like a very simple algorithm.

If you run this code, calculator will pop-up 3 times on Desktop. Sure, we can run other apps, not just calc:


import os

x = 0

while x <= 3:
    os.system("calc")
    x = x + 1

In next tutorial, we will learn about Break and Continue options when looping with While Loops.

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 .  ...