Skip to main content

Python Loops

Use these exercises to practice working with conditional statements, while loops, and Lists in Python.

Must Haves

  • Create a new folder, initialize a git repository
  • Create a separate file for each section (file names are listed per section)

While Loop

Save these in a file called loops.py.

Start/End

  • Ask the user for a starting number, assign it to a variable.
  • Ask the user for an ending number, assign it to a variable.
  • Write a loop that increments the starting number by 1 until it matches the ending number.
Solution
  start = int(input("Start from: "))
end = int(input("End on: "))

count = start

while count <= end:
print(count)
count += 1

Multi-Condition Check

  • Create string with at least 2 words and at least 16 characters total.
  • Create a variable called counter with a starting value of 0
  • Loop through the string
    • Increment the counter by 1
    • Stop the loop when counter is greater than the length of your string.
  • IN THE LOOP
    • Write a condition to see If the counter value is an even number.
    • Also make sure the value of your string at the index of counter isn't a blank space!
    • If both of those conditions are met, print the value of your string at that counter position
  • The result should be only letters that occur in even numbered indexes.
Solution
title = "Green Lantern Corp"
counter = 0
while counter < len(title):
# print out every other letters, but leave out spaces
if (counter % 2) == 0 and title[counter] != " ":
print(title[counter])
counter = counter + 1

Bonus

  • Can you write a loop that increments by more than 1?
  • Can you create a range of numbers from which the user can choose?
  • Can you let the user know when they choose something out of that range?
Solution
# Can you write a loop that increments by more than `1`?

while count <= end:
print(count)
count += 5


# Can you create a range of numbers from which the user can choose?

def check_in_range(num):
if num >= 1 and num <= 5:
return True
else:
return False

# Can you let the user know when they choose something out of that range?

def throw_error(value_type):
return "Please choose a different {} value".format(value_type)

running = True
while running == True:
start = int(input("Pick a number from 1-5 to start from: "))
end = int(input("Pick a number from 1-5 to end on: "))

if check_in_range(start) == True and check_in_range(end) == True:
if end <= start:
print(throw_error("end"))
while start <= end:
print(start)
start += 1
if start == end:
running = False
else:
if check_in_range(start) == False:
print(throw_error("start"))
if check_in_range(end) == False or end >= start:
print(throw_error("end"))