Skip to content

While loop (while)

A process that will repeat many time if meet the condition.

  • When the condition is True means run / continue the looping, when condition become False it will stop the looping

Format

while meet_condition:
    task_1
    task_2
  • The loop will be continued until the condition is no longer True
  • The condition must return Boolean results.

Usage

Example: print 1 - 100 to console.

At this point, it's still possible to put 100 print() function, but when the range increases it becomes not so reality, so we're using loop for repeat action.


while-loop.py

py
number = int(1)

while number <= 100:
    print(number)
    number += 1

Notes

  • number <= 100 is the condition to control the looping process
  • number += 1 will change the condition, so that infinite looping will not occured

Results:

print 1 until 100 on every line

1
2
3
4
5
...
95
96
97
98
99
100

Example 2: Find sum of 1 to 100,

1 + 2 + 3 + ... + 99 + 100

  • n = 100
  • a = 1
  • d = 1

Sn=n2[2a+(n1)d]S_n = \frac{n}{2}[2a + (n - 1)d]


S100=1002[2(1)+(1001)1]=5050S_{100} = \frac{100}{2}[2{(1)} + (100 - 1)1] = 5050

while-loop-2.py

py
# sum of ap

a = 1
n = 100
d = 1

sum_of_ap = (n / 2) * ((2 * a) + (d * (n - 1)))

# since all value are int so it should be int
print("Sum of 1..100 (AP):", int(sum_of_ap))

# sum of 1...100 by while loop

while_sum = 0
number = 1

while number <= 100:
    while_sum += number
    number += 1

print("Sum of 1..100 (While loop):", while_sum)

Results:

Sum of 1..100 (AP): 5050
Sum of 1..100 (While loop): 5050

Extra: Improvement of number guessing

Changes: now the guessing opportunity become unlimited, but still giving hints if guess the wrong number.

improvement-of-number-guessing-while.py

py
import random

random_num = random.randint(1, 10)
ans = int(input("Please guess a number in between 1 - 10: "))

while ans != random_num:

    print("You have guessed the number wrongly, Try again !")

    if ans > random_num:
        print(f"The number is lower than {ans}")
    else:
        print(f"The number is greater than {ans}")

    ans = int(input("Please guess a number again: "))

print("You guessed the number correctly !")

Results:

Please guess a number in between 1 - 10: 5
You have guessed the number wrongly, Try again !
The number is greater than 5
Please guess a number again: 9
You have guessed the number wrongly, Try again !
The number is lower than 9
Please guess a number again: 3
You have guessed the number wrongly, Try again !
The number is greater than 3
Please guess a number again: 6
You guessed the number correctly !

Version with 3 opportunity

improvement-of-number-guessing-while-2.py

py
import random

random_num = random.randint(1, 10)
ans = int(input("Please guess a number in between 1 - 10 (You have 3 opportunities): "))
number_of_trial = int(1)

while ans != random_num:

    if number_of_trial == 3:
        print("You failed")
        break

    print("You have guessed the number wrongly, Try again !")

    if ans > random_num:
        print(f"The number is lower than {ans}")
    else:
        print(f"The number is greater than {ans}")

    ans = int(input("Please guess a number again: "))
    number_of_trial += 1

if number_of_trial < 3:
    print("You guessed the number correctly !")

Results:

Please guess a number in between 1 - 10 (You have 3 opportunities): 1
You have guessed the number wrongly, Try again !
The number is greater than 1
Please guess a number again: 1
You have guessed the number wrongly, Try again !
The number is greater than 1
Please guess a number again: 1
You failed