Start free

GCSE · 8 exercises

Python while loops

A while loop repeats as long as its condition is true: use it when you don't know in advance how many times.

Something inside the loop must change, so the condition becomes false in the end.

n = int(input())
digits = 0
while n > 0:
    n //= 10
    digits += 1
print(digits)

Watch for: If nothing in the loop changes the condition, it never ends and the program is stopped after a few seconds.

Exercises

  1. How many digits?Count the digits of a positive whole number using a while loop and // 10 (not len).Beginner
  2. Sum of the digitsAdd up the digits of a whole number of any length using a while loop.Beginner
  3. Reverse a numberRead a positive whole number and print its digits in reverse order, as a numberBeginner
  4. Add until zeroKeep reading numbers and adding them up until you read 0.Beginner
  5. Guess the numberThe first line is a secret number.Beginner
  6. Collatz stepsStart with n.Beginner
  7. Saving upYou save the same amount every month.Beginner
  8. Money doublesMoney in a bank grows by a fixed percentage every year.Beginner
Start with “How many digits?”