Python · Syntax · Beginner
While loop
Python while loop exercises: repeating actions, counters, summing numbers, entering until a condition, break, looping through strings, and basic character processing.
Quick topic start and explanations before exercises (exercises below):
Counters, accumulators, and the sentinel pattern
#Iterating through strings with while
#While loop quick reference
#Exercises:
Numbers from 1 to 10.
#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.
Countdown from 10.
#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
Numbers up to the entered value.
#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)
Only even numbers up to the 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
Sum from 1 to 100.
#i = 1 total = 0
Solution
i = 1
total = 0
while i <= 100:
total += i
i += 1
print("Sum:", total)
Sum up to the entered 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)
Multiplication table.
#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
Password until correct input.
#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.
Sum of numbers until zero.
#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)
Counting digits in a number.
#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)
Word backwards.
#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
Text between identical characters.
#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)
Letter stairs.
#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
Removing punctuation from text.
#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)