Loops Project Solutions
Level 1: Repeat Repeat Repeat
Level 2: Times Table
Level 3: Data Cleaner
Level 1: Repeat Repeat Repeat
Goal: Ask for a word and a number, print the word that many times with numbers
Step 1: Ask for a word and a number
word = input("Enter a word to repeat: ")
num = input("How many times should it repeat? ")
word stores the text the user wants to repeat.
num is a String that represents the number of times word should repeat.
Step 2: Convert the number to an integer and make sure it is valid.
num = int(num)
if num <= 0:
print("Please enter a number greater than 0.")
We have to convert num to an integer with int(num). Then, we check if the number is positive or not, since we cannot repeat a word a negative or 0 amount of times.
Step 3: Use a for loop to print the word with numbers
for i in range(1, num + 1):
print(i, word)
range(1, num + 1) gives the sequence 1, 2, ..., num. i is the loop counter, so we print "1 word", "2 word", etc.
Level 2: Times Table
Goal: Ask a user for a number, and create a table with that many rows and columns with each item being a product of the row and column number.
Step 1: Ask for the table size
size = input("Create a times table up to: ")
size should be something like "5" or "10".
Step 2: Convert it to an integer and validate
size = int(size)
if size <= 0:
print("Please enter a number greater than 0")
else:
# continue with building the table
Again, we have to convert the String size to an integer using int(size). We also only accept positive integers.
Step 3: Use nested loops to build the table
for r in range(1, size + 1):
for c in range(1, size + 1):
product = r * c
print(product, end="\t")
print()
The outer loop picks a row number, r, and the inner loop picks a column number, c. Multiply them to get the value in the table, which is done with product = r * c, and finally print the product with a tab character to end the line instead of a newline character, done by doing end="\t". This will keep the values on the same row, and then once one row is finished print() moves to the next line.
Level 3: Data Cleaner
Goal: Given a list of mixed inputs (strings, booleans, numbers), convert everything to floats and get rid of everything else. Count how many are valid, invalid, and the percentage of valid inputs.
Topics: Lists, loops, booleans, error handling
Step 1: Start with a mixed list
data = [10, "3.5", "hello", True, "7", False, "apple", 2.5, "0", "5.0", "nope"]
This list contains Integers, Floats, Strings that look like numbers, Strings that don't, and Booleans.
Step 2: Create lists and counters for results
cleaned = []
valid_cnt = 0
invalid_cnt = 0
cleaned will hold all the successfully converted floats. valid_cnt and invalid_cnt are counter variables.
Step 3: Loop through each item and try to convert to float
for item in data:
try:
value = float(item)
cleaned.append(value)
valid_cnt += 1
except (ValueError, TypeError):
invalid_cnt += 1
We loop through each item with the line for item in data. We try a block of code to test it for errors, and the except block will handle the errors. float(item) works for numbers, booleans (True→1.0, False→0.0), and numeric strings ("3.5", "7"), but it fails for non-numeric strings like "hello", which goes to the except block. We count successes using valid_cnt += 1, and failures as invalid_cnt += 1.
Step 4: Calculate totals and percentages
total_items = len(data)
if total_items > 0:
percent_valid = (valid_cnt / total_items) * 100
else:
percent_valid = 0
total_items is how many values we started with, using len(data) to find it, and the percentage is (valid_cnt / total_items) * 100.
Step 5: Print the final results
print("Cleaned floats:", cleaned)
print("Valid count:", valid_cnt)
print("Invalid count:", invalid_cnt)
print(f"Percent valid: {percent_valid:.2f}%")
We print out the cleaned list, the valid and invalid totals, and {percent_valid:.2f}% prints the percentage with 2 decimal places.