Python · Syntax · Beginner

While loop

14 tasks

Python while loop exercises: repeating actions, counters, summing numbers, entering until a condition, break, looping through strings, and basic character processing.

How the while loop works

#
The while loop keeps running its body as long as a condition is True. Unlike for, which visits each item in a sequence, while keeps going until something makes the condition False. ```python i = 1 while i <= 10: print(i) i += 1 ``` Python checks the condition before every iteration, including the first. If the condition is False at the start, the body never runs at all. The most common mistake with while loops is forgetting to update whatever the condition depends on. If i never changes, i <= 10 stays True forever — an infinite loop. Always make sure something inside the loop moves you toward the exit condition. break exits the loop immediately, regardless of the condition. It is useful when the exit point is in the middle of the loop body rather than at the top: ```python while True: password = input("Enter password: ") if password == "python": break print("Wrong, try again") ``` while True is an intentional infinite loop that relies entirely on break to stop. This pattern is standard for "keep asking until valid input."

Counters, accumulators, and the sentinel pattern

#
Three patterns appear across almost all while-loop exercises. Counter: start a variable at some value, increment or decrement it each iteration, stop when it reaches a boundary. ```python i = 1 while i <= 10: print(i) i += 1 ``` Accumulator: start a total at zero, add each value to it inside the loop. ```python i = 1 total = 0 while i <= 100: total += i i += 1 print(total) ``` Sentinel: keep reading input until the user provides a stop signal (like 0). Read the first value before the loop, then read again at the end of the body so the next check uses the new value. ```python total = 0 num = int(input("Enter a number (0 to stop): ")) while num != 0: total += num num = int(input("Enter a number (0 to stop): ")) print(total) ``` These three patterns combine. A multiplication table uses a counter and prints an expression each step. A password loop uses a sentinel. A digit counter uses a counter and integer division to peel digits off one at a time.

Iterating through strings with while

#
The while loop also works well for iterating through strings by index when you need more control than a for loop gives you — for example, moving backwards or jumping by more than one step. Printing a string in reverse using a while loop: ```python word = "Python" i = len(word) - 1 while i >= 0: print(word[i], end="") i -= 1 ``` i starts at the index of the last character and counts down to 0. end="" keeps everything on one line. Stripping characters one at a time — useful for building filtered strings: ```python punctuation = "!@#$%^&./,?|" text = "Hello, world!" result = "" i = 0 while i < len(text): if text[i] not in punctuation: result += text[i] i += 1 print(result) ``` text[i] not in punctuation uses the same in operator you saw with strings, but testing membership in another string. Every character in punctuation counts as a "substring", so this correctly identifies each special character.

While loop quick reference

#
**while loop syntax** ```python while condition: # body — runs as long as condition is True # with break and continue while condition: if some_case: break # exit the loop immediately if other_case: continue # skip the rest of this iteration, re-check condition # normal body ``` **Three core patterns** | Pattern | Setup | Update inside loop | Purpose | |---|---|---|---| | Counter | `i = start` | `i += 1` or `i -= 1` | iterate a fixed number of times | | Accumulator | `total = 0` | `total += value` | sum / build up a result | | Sentinel | read first value before loop | read again at end of body | stop on a special input | ```python # Counter i = 1 while i <= 10: print(i) i += 1 # Accumulator total = 0 while i <= n: total += i i += 1 # Sentinel num = int(input('Number (0 to stop): ')) while num != 0: total += num num = int(input('Number (0 to stop): ')) ``` **`while True` + `break` — ask until valid** ```python while True: answer = input('yes or no? ') if answer in ('yes', 'no'): break print('Please type yes or no') ``` **Common mistakes** ```python # Infinite loop — i never changes: i = 1 while i <= 10: print(i) # forgot i += 1 # Off-by-one — use <= not < to include the last value: while i < 10: # stops at 9 while i <= 10: # stops at 10 ```
01

Numbers from 1 to 10.

#

Print the numbers from 1 to 10 using a while loop.

i = 1

Solution
i = 1

while i <= 10:
    print(i)
    i += 1


# or for example you can place the condition inside the loop in if statements
# and stop the loop using break. In this case the first option is of course better,
# but you should look at different variants to expand your imagination:

i = 1

while True:
    if i <= 10:
        print(i)
        i += 1
    else:
        break

# the same thing, just organized differently:

i = 1

while True:
    if i > 10:
        break
    print(i)
    i += 1
# in this case else is not needed (it is simply unnecessary), because
# when break executes, the loop will stop.


# this was to expand your imagination with different variants.
02

Countdown from 10.

#

Print the numbers from 10 to 1 in reverse order.

i = 10

Solution
i = 10

while i >= 1:
    print(i)
    i -= 1

# or you can do this: use the condition greater than zero
i = 10

while i > 0:
    print(i)
    i -= 1
03

Numbers up to the entered value.

#

The user enters a number. Print all numbers from 1 to this number.

n = int(input("Enter a number: "))
i = 1

Solution
n = int(input("Enter a number: "))
i = 1

while i <= n:
    print(i)
    i += 1

# or you can do this: start from zero, but print the next number
n = int(input("Enter a number: "))
i = 0

while i < n:
    i += 1
    print(i)
04

Only even numbers up to the number.

#

The user enters a number. Print only even numbers from 1 to this number.

n = int(input("Enter a number: "))
i = 1

Solution
n = int(input("Enter a number: "))
i = 1

while i <= n:
    if i % 2 == 0:
        print(i)
    i += 1

# second option: immediately go only through even numbers
n = int(input("Enter a number: "))
i = 2

while i <= n:
    print(i)
    i += 2
05

Sum from 1 to 100.

#

Find the sum of all numbers from 1 to 100 using a while loop.

i = 1
total = 0
Solution
i = 1
total = 0

while i <= 100:
    total += i
    i += 1

print("Sum:", total)
06

Sum up to the entered number.

#

The user enters a number. Find the sum of all numbers from 1 to this number.

n = int(input("Enter a number: "))
i = 1
total = 0

Solution
n = int(input("Enter a number: "))
i = 1
total = 0

while i <= n:
    total += i
    i += 1

print("Sum:", total)

# or you can do this: add the number and decrease it
n = int(input("Enter a number: "))
total = 0

while n > 0:
    total += n
    n -= 1

print("Sum:", total)
07

Multiplication table.

#

The user enters a number. Display the multiplication table for this number from 1 to 10.

n = int(input("Enter a number: "))
i = 1

Solution
n = int(input("Enter a number: "))
i = 1

while i <= 10:
    print(f"{n} x {i} = {n * i}")
    i += 1

# or you can do this: calculate the product first
n = int(input("Enter a number: "))
i = 1

while i <= 10:
    result = n * i
    print(f"{n} x {i} = {result}")
    i += 1
08

Password until correct input.

#

The user enters a password. Keep asking for the password until it equals "python".

password = input("Enter password: ")

Solution
password = input("Enter password: ")

while password != "python":
    password = input("Incorrect. Enter the password again: ")

print("Password accepted")


# OR
password = input("Enter password: ")

while True:
    if password == "python":
        break
    password = input("Incorrect. Enter the password again: ")

print("Password accepted")

# AGAIN I will repeat this point, which sometimes causes problems in understanding:
1) Creating (or recreating) variables inside a loop is allowed, like password = ...
When entering a new "iteration" of the loop, the value in the variable will simply be replaced with a new one.
For example, a loop that endlessly prints the numbers from 1 to 5 in the terminal:

num = 1

while True:
    if num == 6:
        num = 1
    print(num)
    num += 1
    input() # just to slow execution until any input.
            # input is not saved anywhere and is not used.
09

Sum of numbers until zero.

#

The user enters numbers. The program should calculate the sum of the entered numbers until the user enters 0.

total = 0
num = int(input("Enter a number: "))

Solution
total = 0
num = int(input("Enter a number: "))

while num != 0:
    total += num
    num = int(input("Enter a number: "))

print("Sum:", total)

# or like this:

total = 0

while True:
    num = int(input("Enter a number: "))
    if num == 0:
        break
    total += num

print("Sum:", total)
10

Counting digits in a number.

#

The user enters a number. Count how many digits are in this number. You may solve it without a loop in any way.

num = int(input("Enter a number: "))
count = 0

Solution
num = int(input("Enter a number: "))
count = 0

if num == 0:
    count = 1
else:
    if num < 0:
        num = -num  # change the sign to + (- times - equals +)

    while num > 0:
        count += 1
        num //= 10

print("Number of digits:", count)

# or you can do this without a loop, if you remember the string representation of a number
num = int(input("Enter a number: "))

text = str(abs(num))
count = len(text)

print("Number of digits:", count)
11

Word backwards.

#

Print the word backwards in the terminal in several ways: - using a slice (to review it); - using a while loop a) by forming a new "reversed" string object using a loop and indexes; b) by printing characters from the end without line breaks in the terminal (the end= parameter of print)

word = "иладеп"

Solution
# 1)
word = "иладеп"
print(word[::-1])


# 2)
word = "иладеп"

drow = ""
index = len(word) - 1
while index > -1:
    drow += word[index]
    index -= 1
print(drow)


# 3)
word = "иладеп"

index = len(word) - 1
while index > -1:
    print(word[index], end="")
    index -= 1
else:
    print()  # move to a new line in the terminal at the end
12

Text between identical characters.

#

I probably got carried away here and this task is probably not easy. But that's okay, let's slowly think step by step about what needs to be done. Condition: There is a string with any information, for example: 'Company LLC "Horns and Hooves" won some procurement thing.' We need to cut out the piece between some identical characters. For example in this case, to get the company name, we need to cut out the text between quotation marks. Do not use the split string method. Use only the index method!! You can experiment and solve the task without a loop and with a loop, however you like. P.S. You will need slices, and make text input and character input between repetitions of which to cut out via input. P.P.S See the string methods table. The index method returns the index of the FIRST occurrence of a character in a string (it does not return the second one (unless you "hack" it so it becomes the first in some intermediate string)).

text = input("Enter text: ")
symbol = input("Enter the symbol at the edges of the text fragment: ")
Solution
text = input("Enter text: ")
symbol = input("Enter the symbol at the edges of the text fragment: ")

start_index = text.index(symbol) + 1 # got the start index

new_text = ""
while start_index < len(text):
    char = text[start_index]  # take a character from the text
    if char == symbol:  # when the "second" symbol is encountered, that's it.
        break
    new_text += char
    start_index += 1

print(new_text)


# OR using only slices. Be careful with indexes and the intermediate string.
text = input("Enter text: ")
symbol = input("Enter the symbol at the edges of the text fragment: ")

start = text.index(symbol) + 1 # got the start index

# let's immediately slice from this point to the end of the text:
part = text[start:] # slice from start to the end

stop = part.index(symbol)  # get the index of the second occurrence of symbol

result = text[start:stop + start]
# or
result = part[:stop]

print(result)
13

Letter stairs.

#

Everything is simple here: There is a string "stairs", print it in the terminal like this: s -t --a ---i ----r -----s

text = "ступеньки"
Solution
text = "stairs"

# first option:
index = 0
while index < len(text):
    for_print = "-" * index + text[index]
    print(for_print)
    index += 1


# second option:
index = 0
while index < len(text):
    # the rjust string method adds characters on the left up to the required length
    char = text[index]
    for_print = char.rjust(index+1, " ")
    print(for_print)
    index += 1


# shortened second option, the same thing, apply the method directly to the character object:
index = 0
while index < len(text):
    for_print = text[index].rjust(index+1, " ")
    print(for_print)
    index += 1


# stairs backwards:
text = text[::-1]
index = 0
while index < len(text):
    for_print = text[index].rjust(len(text) - index, " ")
    print(for_print)
    index += 1
14

Removing punctuation from text.

#

There is a list of punctuation marks and special characters: punctuation = "!@#$%^&./,?|" And there is a text string in which they may appear. Create a new string without punctuation marks, leaving only the text, keep spaces. That's all that needs to be done.

punctuation = "!@#$%^&./,?|"
text = "I guess we will finish with this exercise. Enough! We want to rest! #@&#@&!!!"
Solution
punctuation = "!@#$%^&./,?|"
text = "I guess we will finish with this exercise. Enough! We want to rest! #@&#@&!!!"


new_text = ""

idx = 0
while idx < len(text):
    char = text[idx]
    if char not in punctuation:
        new_text += char
    idx += 1
else:
    text = text.strip()  # clean spaces from the sides. Only from the sides.

print(new_text)