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.
#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.
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
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)
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
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)
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)
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
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.
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)
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)
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
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)
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
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)