Skip to content

A2 - Python Looping Review

Reference for this assignment

Python Manual - Page 6

Learning Goals

  • Use a while loop to validate input
  • Use a for loop to go through list items

Suggested Task

Part A

Consider the following program, that uses a while loop to ensure the user follows the instructions to enter in a number between 1 and 10.

response = input("Enter a number between 1 and 10: ")

while not response.isdigit() or int(response) < 1 or int(response) > 10:
    response = input("Invalid Input. Enter a number between 1 and 10: ")

print(f"Your response of {response} is valid")

Write a similar program, but instead of asking for a number between 1 and 10, change the condition. Consider something that isn't trivial - for example, you could ask for an even number greater than 100. You may find some of the string method on page 9 of the Python manual useful, although using these are optional.

Part B

Copy the following code into a new Python file:

nums = [3, 11, 30, 8, 2, 25, 32]
for num in nums:
    if num > 10:
        print(num)

Change the condition of the if statement so that a different subset of the list is printed.

Optional Extension

There's lots of variations of things you can do inside these type of loops. For example, consider the following:

nums = [3, 11, 30, 8, 2, 25, 32]
for num in nums:
    if num > 10:
        print(f"{num} is greater than 10, and the last digit of the number is {num%10}")
    else:
        print(f"{num} is less than or equal to 10, and the last digit of the number is {num%10}")

What unique variation could you come up with? Feel free to use a previous example as a starting point, or start from scratch!