DEV Community

Deva I
Deva I

Posted on

Looping programs using Python

The sum of first n numbers :

CODE :

result = 0
no = 1

while no <= 5:
    result = result + no
    no += 1

print(result)
Enter fullscreen mode Exit fullscreen mode

EXPLANATION :

✓ Initial State: result = 0, no =1

✓ STEP 1: no is (1). result becomes (0 + 1 = 1). no becomes (2).

✓ STEP 2: no is (2). result becomes (1 + 2 = 3). no becomes (3).

✓ STEP 3: no is (3). result becomes (3 + 3 = 6). no becomes (4).

✓ STEP 4: no is (4). result becomes (6 + 4 = 10). no becomes (5).

✓ STEP 5: no is (5). result becomes (10 + 5 = 15). no becomes (6).

✓ Finally the no becomes 6 (no <=5).false,so break the loop and print the result.

Factorial program (5!) :

CODE :

result = 1
no = 5

while no >= 1:
    result = result * no
    no -= 1

print(result)
Enter fullscreen mode Exit fullscreen mode

EXPLANATION :

✓ Initial State: result = 1, no = 5

✓ STEP 1: result = 1 * 5, Then no is = 4,

✓ STEP 2:Then the result(5) = 5 * 4, Then no becomes = 3,

✓ STEP 3: Then the result is = 20 * 3, no becomes = 2,

✓ STEP 4: Then the result = 60 * 2, no becomes = 1,

✓ STEP 5:Now, the result is = 120* 1, no becomes = 0

✓ Finally the no is 0.(no >= 1), condition is false, then break the loop and Print the result.

A frog is fallen the well mistakenly.so it tries to go on out using the wall to move upwards 2 feets and downwards 1 feet each day,the question is howmany days takes the frog to going out the well ?

CODE :

feet = 50
days = 0
up = 2
down = 1

while feet > 0:
    feet = feet - up + down
    days += 1

print("Days:", days) 

Enter fullscreen mode Exit fullscreen mode

✓ Initial state: feet,days-0,up-2 and down-1

✓ feet is 50,that's satisfy the condition of (feet > 0),true.feet=(50-2+1)= 49.Then the feet becomes 49.

✓ This process happens untill the feet gets 0

✓ When the feet becomes 0,the loop break and print days.

Top comments (0)