Chapter 7: User Input and while Loops

Source: Python Crash Course, 3rd Edition by Eric Matthes

Most programs are written to solve an end user’s problem. To do so, you usually need to get some information from the user. For example, say someone wants to find out whether they’re old enough to vote. If you write a program to answer this question, you need to know the user’s age before you can provide an answer. The program will need to ask the user to enter, or input, their age; once the program has this input, it can compare it to the voting age to determine if the user is old enough and then report the result.

In this chapter you’ll learn how to accept user input so your program can then work with it. When your program needs a name, you’ll be able to prompt the user for a name. When your program needs a list of names, you’ll be able to prompt the user for a series of names. To do this, you’ll use the input() function.

You’ll also learn how to keep programs running as long as users want them to, so they can enter as much information as they need to; then, your program can work with that information. You’ll use Python’s while loop to keep programs running as long as certain conditions remain true.

With the ability to work with user input and the ability to control how long your programs run, you’ll be able to write fully interactive programs.

How the input() Function Works

The input() function pauses your program and waits for the user to enter some text. Once Python receives the user’s input, it assigns that input to a variable to make it convenient for you to work with.

For example, the following program asks the user to enter some text, then displays that message back to the user:

parrot.py
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

The input() function takes one argument: the prompt that we want to display to the user, so they know what kind of information to enter. In this example, when Python runs the first line, the user sees the prompt Tell me something, and I will repeat it back to you:. The program waits while the user enters their response and continues after the user presses Enter. The response is assigned to the variable message, then print(message) displays the input back to the user:

Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone!

Some text editors won’t run programs that prompt the user for input. You can use these editors to write programs that prompt for input, but you’ll need to run these programs from a terminal. See Running Python Programs from a Terminal on page 11.

Writing Clear Prompts

Each time you use the input() function, you should include a clear, easy-to-follow prompt that tells the user exactly what kind of information you’re looking for. Any statement that tells the user what to enter should work. For example:

greeter.py
name = input("Please enter your name: ")
print(f"Hello, {name}!")

Add a space at the end of your prompts (after the colon in the preceding example) to separate the prompt from the user’s response and to make it clear to your user where to enter their text. For example:

Please enter your name: Eric
Hello, Eric!

Sometimes you’ll want to write a prompt that’s longer than one line. For example, you might want to tell the user why you’re asking for certain input. You can assign your prompt to a variable and pass that variable to the input() function. This allows you to build your prompt over several lines, then write a clean input() statement.

greeter.py
prompt = "If you share your name, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print(f"\nHello, {name}!")

This example shows one way to build a multiline string. The first line assigns the first part of the message to the variable prompt. In the second line, the operator += takes the string that was assigned to prompt and adds the new string onto the end.

The prompt now spans two lines, again with space after the question mark for clarity:

If you share your name, we can personalize the messages you see.
What is your first name? Eric

Hello, Eric!

Using int() to Accept Numerical Input

When you use the input() function, Python interprets everything the user enters as a string. Consider the following interpreter session, which asks for the user’s age:

>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'

The user enters the number 21, but when we ask Python for the value of age, it returns '21', the string representation of the numerical value entered. We know Python interpreted the input as a string because the number is now enclosed in quotes. If all you want to do is print the input, this works well. But if you try to use the input as a number, you’ll get an error:

>>> age = input("How old are you? ")
How old are you? 21
>>> age >= 18                                          (1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'  (2)
1 When you try to use the input to do a numerical comparison, Python produces an error.
2 Python can’t compare a string to an integer: the string '21' assigned to age can’t be compared to the numerical value 18.

We can resolve this issue by using the int() function, which converts the input string to a numerical value. This allows the comparison to run successfully:

>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)   (1)
>>> age >= 18
True
1 The value is converted to a numerical representation by int(). Now Python can run the conditional test: it compares age (which now represents the numerical value 21) and 18 to see if age is greater than or equal to 18.

How do you use the int() function in an actual program? Consider a program that determines whether people are tall enough to ride a roller coaster:

rollercoaster.py
height = input("How tall are you, in inches? ")
height = int(height)

if height >= 48:
    print("You're tall enough to ride!")
else:
    print("You'll be able to ride when you're a little older.")

The program can compare height to 48 because height = int(height) converts the input value to a numerical representation before the comparison is made. If the number entered is greater than or equal to 48, we tell the user that they’re tall enough:

How tall are you, in inches? 71

You're tall enough to ride!

When you use numerical input to do calculations and comparisons, be sure to convert the input value to a numerical representation first.

The Modulo Operator

A useful tool for working with numerical information is the modulo operator (%), which divides one number by another number and returns the remainder:

>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
1

The modulo operator doesn’t tell you how many times one number fits into another; it only tells you what the remainder is.

When one number is divisible by another number, the remainder is 0, so the modulo operator always returns 0. You can use this fact to determine if a number is even or odd:

even_or_odd.py
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2 == 0:
    print(f"The number {number} is even.")
else:
    print(f"The number {number} is odd.")

Even numbers are always divisible by two, so if the modulo of a number and two is zero (here, if number % 2 == 0) the number is even. Otherwise, it’s odd.

Enter a number, and I'll tell you if it's even or odd: 42

The number 42 is even.

Try It Yourself

7-1. Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as Let me see if I can find you a Subaru.

7-2. Restaurant Seating: Write a program that asks the user how many people are in their dinner group. If the answer is more than eight, print a message saying they’ll have to wait for a table. Otherwise, report that their table is ready.

7-3. Multiples of Ten: Ask the user for a number, and then report whether the number is a multiple of 10 or not.

Introducing while Loops

The for loop takes a collection of items and executes a block of code once for each item in the collection. In contrast, the while loop runs as long as, or while, a certain condition is true.

The while Loop in Action

You can use a while loop to count up through a series of numbers. For example, the following while loop counts from 1 to 5:

counting.py
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1

In the first line, we start counting from 1 by assigning current_number the value 1. The while loop is then set to keep running as long as the value of current_number is less than or equal to 5. The code inside the loop prints the value of current_number and then adds 1 to that value with current_number = 1`. (The `= operator is shorthand for current_number = current_number + 1.)

Python repeats the loop as long as the condition current_number ⇐ 5 is true. Because 1 is less than 5, Python prints 1 and then adds 1, making the current number 2. Because 2 is less than 5, Python prints 2 and adds 1 again, making the current number 3, and so on. Once the value of current_number is greater than 5, the loop stops running and the program ends:

1
2
3
4
5

The programs you use every day most likely contain while loops. For example, a game needs a while loop to keep running as long as you want to keep playing, and so it can stop running as soon as you ask it to quit. Programs wouldn’t be fun to use if they stopped running before we told them to or kept running even after we wanted to quit, so while loops are quite useful.

Letting the User Choose When to Quit

We can make the parrot.py program run as long as the user wants by putting most of the program inside a while loop. We’ll define a quit value and then keep the program running as long as the user has not entered the quit value:

parrot.py
prompt = "Tell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
    message = input(prompt)
    print(message)

We first define a prompt that tells the user their two options: entering a message or entering the quit value (in this case, 'quit'). Then we set up a variable message to keep track of whatever value the user enters. We define message as an empty string, "", so Python has something to check the first time it reaches the while line. The first time the program runs and Python reaches the while statement, it needs to compare the value of message to 'quit', but no user input has been entered yet. To solve this problem, we make sure to give message an initial value. Although it’s just an empty string, it will make sense to Python and allow it to perform the comparison that makes the while loop work. This while loop runs as long as the value of message is not 'quit'.

The first time through the loop, message is just an empty string, so Python enters the loop. At message = input(prompt), Python displays the prompt and waits for the user to enter their input. Whatever they enter is assigned to message and printed; then, Python reevaluates the condition in the while statement. As long as the user has not entered the word 'quit', the prompt is displayed again and Python waits for more input. When the user finally enters 'quit', Python stops executing the while loop and the program ends:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit

This program works well, except that it prints the word 'quit' as if it were an actual message. A simple if test fixes this:

prompt = "Tell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
    message = input(prompt)

    if message != 'quit':
        print(message)

Now the program makes a quick check before displaying the message and only prints the message if it does not match the quit value:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello again.
Hello again.

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit

Using a Flag

In the previous example, we had the program perform certain tasks while a given condition was true. But what about more complicated programs in which many different events could cause the program to stop running?

For example, in a game, several different events can end the game. When the player runs out of ships, their time runs out, or the cities they were supposed to protect are all destroyed, the game should end. It needs to end if any one of these events happens. If many possible events might occur to stop the program, trying to test all these conditions in one while statement becomes complicated and difficult.

For a program that should run only as long as many conditions are true, you can define one variable that determines whether or not the entire program is active. This variable, called a flag, acts as a signal to the program. We can write our programs so they run while the flag is set to True and stop running when any of several events sets the value of the flag to False. As a result, our overall while statement needs to check only one condition: whether the flag is currently True. Then, all our other tests can be neatly organized in the rest of the program.

Let’s add a flag to parrot.py from the previous section. This flag, which we’ll call active (though you can call it anything), will monitor whether or not the program should continue running:

prompt = "Tell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program. "

active = True
while active:               (1)
    message = input(prompt)

    if message == 'quit':
        active = False
    else:
        print(message)
1 As long as the active variable remains True, the loop will continue running.

We set the variable active to True so the program starts in an active state. Doing so makes the while statement simpler because no comparison is made in the while statement itself; the logic is taken care of in other parts of the program.

In the if statement inside the while loop, we check the value of message once the user enters their input. If the user enters 'quit', we set active to False, and the while loop stops. If the user enters anything other than 'quit', we print their input as a message.

This program has the same output as the previous example where we placed the conditional test directly in the while statement. But now that we have a flag to indicate whether the overall program is in an active state, it would be easy to add more tests (such as elif statements) for events that should cause active to become False. This is useful in complicated programs like games, in which there may be many events that should each make the program stop running. When any of these events causes the active flag to become False, the main game loop will exit, a Game Over message can be displayed, and the player can be given the option to play again.

Using break to Exit a Loop

To exit a while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test, use the break statement. The break statement directs the flow of your program; you can use it to control which lines of code are executed and which aren’t, so the program only executes code that you want it to, when you want it to.

For example, consider a program that asks the user about places they’ve visited. We can stop the while loop in this program by calling break as soon as the user enters the 'quit' value:

cities.py
prompt = "Please enter the name of a city you have visited: "
prompt += "\n(Enter 'quit' when you are finished.) "

while True:             (1)
    city = input(prompt)

    if city == 'quit':
        break
    else:
        print(f"I'd love to go to {city.title()}!")
1 A loop that starts with while True will run forever unless it reaches a break statement.

The loop in this program continues asking the user to enter the names of cities they’ve been to until they enter 'quit'. When they enter 'quit', the break statement runs, causing Python to exit the loop:

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) New York
I'd love to go to New York!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) San Francisco
I'd love to go to San Francisco!

Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit

You can use the break statement in any of Python’s loops. For example, you could use break to quit a for loop that’s working through a list or a dictionary.

Using continue in a Loop

Rather than breaking out of a loop entirely without executing the rest of its code, you can use the continue statement to return to the beginning of the loop, based on the result of a conditional test. For example, consider a loop that counts from 1 to 10 but prints only the odd numbers in that range:

counting.py
current_number = 0
while current_number < 10:
    current_number += 1          (1)
    if current_number % 2 == 0:
        continue

    print(current_number)
1 Once inside the loop, we increment the count by 1, so current_number is 1. The if statement then checks the modulo of current_number and 2. If the modulo is 0 (which means current_number is divisible by 2), the continue statement tells Python to ignore the rest of the loop and return to the beginning.
1
3
5
7
9

Avoiding Infinite Loops

Every while loop needs a way to stop running so it won’t continue to run forever. For example, this counting loop should count from 1 to 5:

counting.py
x = 1
while x <= 5:
    print(x)
    x += 1

However, if you accidentally omit the line x += 1, the loop will run forever:

# This loop runs forever!
x = 1
while x <= 5:
    print(x)

Now the value of x will start at 1 but never change. As a result, the conditional test x ⇐ 5 will always evaluate to True and the while loop will run forever, printing a series of 1s:

1
1
1
1
--snip--

Every programmer accidentally writes an infinite while loop from time to time, especially when a program’s loops have subtle exit conditions. If your program gets stuck in an infinite loop, press Ctrl+C or just close the terminal window displaying your program’s output.

To avoid writing infinite loops, test every while loop and make sure the loop stops when you expect it to. If you want your program to end when the user enters a certain input value, run the program and enter that value. If the program doesn’t end, scrutinize the way your program handles the value that should cause the loop to exit. Make sure at least one part of the program can make the loop’s condition False or cause it to reach a break statement.

VS Code, like many editors, displays output in an embedded terminal window. To cancel an infinite loop, make sure you click in the output area of the editor before pressing Ctrl+C.

Try It Yourself

7-4. Pizza Toppings: Write a loop that prompts the user to enter a series of pizza toppings until they enter a 'quit' value. As they enter each topping, print a message saying you’ll add that topping to their pizza.

7-5. Movie Tickets: A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.

7-6. Three Exits: Write different versions of either Exercise 7-4 or 7-5 that do each of the following at least once: use a conditional test in the while statement to stop the loop; use an active variable to control how long the loop runs; use a break statement to exit the loop when the user enters a 'quit' value.

7-7. Infinity: Write a loop that never ends, and run it. (To end the loop, press Ctrl+C or close the window displaying the output.)

Using a while Loop with Lists and Dictionaries

So far, we’ve worked with only one piece of user information at a time. We received the user’s input and then printed the input or a response to it. The next time through the while loop, we’d receive another input value and respond to that. But to keep track of many users and pieces of information, we’ll need to use lists and dictionaries with our while loops.

A for loop is effective for looping through a list, but you shouldn’t modify a list inside a for loop because Python will have trouble keeping track of the items in the list. To modify a list as you work through it, use a while loop. Using while loops with lists and dictionaries allows you to collect, store, and organize lots of input to examine and report on later.

Moving Items from One List to Another

Consider a list of newly registered but unverified users of a website. After we verify these users, how can we move them to a separate list of confirmed users? One way would be to use a while loop to pull users from the list of unconfirmed users as we verify them and then add them to a separate list of confirmed users. Here’s what that code might look like:

confirmed_users.py
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']  (1)
confirmed_users = []

# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:                           (2)
    current_user = unconfirmed_users.pop()         (3)

    print(f"Verifying user: {current_user.title()}")
    confirmed_users.append(current_user)           (4)

# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
1 We begin with a list of unconfirmed users (Alice, Brian, and Candace) and an empty list to hold confirmed users.
2 The while loop runs as long as the list unconfirmed_users is not empty.
3 The pop() method removes unverified users one at a time from the end of unconfirmed_users.
4 Each verified user is added to the confirmed_users list.

Because Candace is last in the unconfirmed_users list, her name will be the first to be removed, assigned to current_user, and added to the confirmed_users list. Next is Brian, then Alice.

We simulate confirming each user by printing a verification message and then adding them to the list of confirmed users. As the list of unconfirmed users shrinks, the list of confirmed users grows. When the list of unconfirmed users is empty, the loop stops and the list of confirmed users is printed:

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

Removing All Instances of Specific Values from a List

In Chapter 3, we used remove() to remove a specific value from a list. The remove() function worked because the value we were interested in appeared only once in the list. But what if you want to remove all instances of a value from a list?

Say you have a list of pets with the value 'cat' repeated several times. To remove all instances of that value, you can run a while loop until 'cat' is no longer in the list, as shown here:

pets.py
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)

We start with a list containing multiple instances of 'cat'. After printing the list, Python enters the while loop because it finds the value 'cat' in the list at least once. Once inside the loop, Python removes the first instance of 'cat', returns to the while line, and then reenters the loop when it finds that 'cat' is still in the list. It removes each instance of 'cat' until the value is no longer in the list, at which point Python exits the loop and prints the list again:

['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

Filling a Dictionary with User Input

You can prompt for as much input as you need in each pass through a while loop. Let’s make a polling program in which each pass through the loop prompts for the participant’s name and response. We’ll store the data we gather in a dictionary, because we want to connect each response with a particular user:

mountain_poll.py
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True

while polling_active:
    # Prompt for the person's name and response.
    name = input("\nWhat is your name? ")             (1)
    response = input("Which mountain would you like to climb someday? ")

    # Store the response in the dictionary.
    responses[name] = response                        (2)

    # Find out if anyone else is going to take the poll.
    repeat = input("Would you like to let another person respond? (yes/no) ")  (3)
    if repeat == 'no':
        polling_active = False

# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():              (4)
    print(f"{name} would like to climb {response}.")
1 Within the loop, the user is prompted to enter their name and a mountain they’d like to climb.
2 That information is stored in the responses dictionary.
3 The user is asked whether or not to keep the poll running.
4 Once polling is complete, the final code block displays the results.

If you run this program and enter sample responses, you should see output like this:

What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/no) yes

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/no) no

--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Devil's Thumb.

Try It Yourself

7-8. Deli: Make a list called sandwich_orders and fill it with the names of various sandwiches. Then make an empty list called finished_sandwiches. Loop through the list of sandwich orders and print a message for each order, such as I made your tuna sandwich. As each sandwich is made, move it to the list of finished sandwiches. After all the sandwiches have been made, print a message listing each sandwich that was made.

7-9. No Pastrami: Using the list sandwich_orders from Exercise 7-8, make sure the sandwich 'pastrami' appears in the list at least three times. Add code near the beginning of your program to print a message saying the deli has run out of pastrami, and then use a while loop to remove all occurrences of 'pastrami' from sandwich_orders. Make sure no pastrami sandwiches end up in finished_sandwiches.

7-10. Dream Vacation: Write a program that polls users about their dream vacation. Write a prompt similar to If you could visit one place in the world, where would you go? Include a block of code that prints the results of the poll.

Summary

In this chapter, you learned how to use input() to allow users to provide their own information in your programs. You learned to work with both text and numerical input and how to use while loops to make your programs run as long as your users want them to. You saw several ways to control the flow of a while loop by setting an active flag, using the break statement, and using the continue statement. You learned how to use a while loop to move items from one list to another and how to remove all instances of a value from a list. You also learned how while loops can be used with dictionaries.

In Chapter 8 you’ll learn about functions. Functions allow you to break your programs into small parts, each of which does one specific job. You can call a function as many times as you want, and you can store your functions in separate files. By using functions, you’ll be able to write more efficient code that’s easier to troubleshoot and maintain and that can be reused in many different programs.

Applied Exercises: Ch 7 — User Input and while Loops

These exercises cover the same concepts as the chapter but use context from real infrastructure, network security, and language learning work. Save each as a separate .py file using lowercase and underscores, e.g. ise_device_prompt.py.

Domus Digitalis / Homelab

D7-1. Node Query: Write a program that prompts the user to enter a node hostname. Print a message like Connecting to: kvm-01. Use a while loop with a quit value so the user can query multiple nodes without restarting the program.

D7-2. VLAN Lookup: Create a dictionary mapping VLAN IDs (as integers) to VLAN names. Write a while True loop that prompts the user to enter a VLAN ID. Convert the input to an integer, look up the VLAN name using get() with a default, and print the result. Use break when the user enters 0.

D7-3. Service Status Queue: Start with a list of services in a pending state. Use a while loop to pop each service, print Checking: <service>, and move it to a checked list. After the loop, print all checked services.

D7-4. BGP Peer Poll: Write a polling program that prompts the user to enter a BGP peer name and its reachability status (up or down). Store the results in a dictionary. Ask after each entry whether to continue. After polling is complete, print a summary showing each peer and its status.

D7-5. Modulo Port Check: Ask the user for a port number. Use the modulo operator to determine whether the port is in the well-known range (below 1024) by checking port % 1024. If the result is less than the input, print Well-known port. Otherwise print Ephemeral or registered port. Loop until the user enters 0.

CHLA / ISE / Network Security

C7-1. Device Prompt: Write a program that prompts the user to enter a device hostname or IP for a health check. Print Running health check on: <device>. Use a while loop with a quit value to allow multiple checks in sequence.

C7-2. Auth Protocol Validator: Use a while True loop that prompts the user to enter an authentication protocol name. If the input matches one of your approved protocols (e.g., EAP-TLS, EAP-TEAP), print Protocol accepted. If not, print Protocol not recognized — try again. Use break when the user enters quit.

C7-3. Log Severity Filter: Ask the user for a minimum syslog severity level (0–7). Convert the input to an integer. Use a flag-based while loop to keep prompting until a valid integer between 0 and 7 is entered. Print Filtering logs at severity <N> and above.

C7-4. Endpoint Verification Queue: Start with a list of endpoint MAC addresses as unverified. Use a while loop to pop each one, print Verifying: <mac>, and append it to a verified list. After the loop, print the count of verified endpoints.

C7-5. Remove Decommissioned Sources: Build a list of log source names that includes 'legacy-syslog' at least three times. Print the list. Use a while loop to remove all occurrences of 'legacy-syslog'. Print the cleaned list and confirm 'legacy-syslog' is no longer present.

General Sysadmin / Linux

L7-1. Package Input: Write a program that prompts the user to enter a package name to install. Print Installing: <package>. Use a while loop with a quit value to simulate installing multiple packages in sequence.

L7-2. Even or Odd Port: Ask the user for a port number. Use the modulo operator to determine whether it’s even or odd and print the result. Use a flag-based while loop to keep prompting until the user enters 0.

L7-3. Service Toggle Queue: Start with a list of service names in a to_restart list. Use a while loop to pop each service, print Restarting: <service>, and move it to a restarted list. After the loop, print all restarted services.

L7-4. User Audit Poll: Write a polling program that prompts the user to enter a username and whether it should be active or disabled. Store results in a dictionary. Ask after each entry whether to continue. Print the audit results when done.

L7-5. Remove Expired Certs: Build a list of certificate names that includes 'expired-cert' at least three times. Use a while loop to remove all occurrences. Print the list before and after.

Spanish / DELE C2

E7-1. Vocabulary Quiz Loop: Write a program that prompts the user to enter the English translation of a Spanish word. Print Procesando: <word>. Use a while loop with a quit value so the user can submit multiple words in one session.

E7-2. Even or Odd Chapter: Ask the user for a Don Quijote chapter number. Use the modulo operator to determine whether it’s even or odd and print Capítulo <N> es par. or Capítulo <N> es impar. Loop until the user enters 0.

E7-3. Study Session Queue: Start with a list of DELE study topics in a pendientes list. Use a while loop to pop each topic, print Estudiando: <tema>, and move it to a completados list. After the loop, print all completed topics.

E7-4. Vocabulary Collection Poll: Write a polling program that prompts the user to enter a Spanish word and its English definition. Store results in a dictionary. Ask after each entry whether to continue. Print all collected vocabulary when done.

E7-5. Remove Mastered Words: Build a list of vocabulary words that includes 'básico' at least three times alongside other words. Print the list. Use a while loop to remove all occurrences of 'básico' (representing words you’ve already mastered and want to retire from review). Print the updated list.