Learn while loop in Python via simple examples.

Example 1: Simple While Loop examle

This example will teach you the following:

  1. How to use while Loop.

Step 1: Create Project

Create python project or file named main.py.

Step 2: Write Code

Add the following code:

# Calculate 1+2+3+...+100:
sum = 0
n = 1
while n <= 100:
    sum  =  sum  +  n
    n = n + 1
print(sum)

# Calculate 1x2x3x...x100:
acc = 1
n = 1
while n <= 100:
    acc = acc * n
    n = n + 1
print(acc)

Step 3: Run

Run the code by navigating to the project directory:

cd your_project_folder

Then execute:

python main.py

You will get the following:

5050
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000