Chapter 7: User Input and While Loops
Programs need user input. While loops handle repetition until conditions change.
The input() Function
input() pauses execution and waits for user input:
hostname = input("Enter server hostname: ")
print(f"Connecting to {hostname}...")
Enter server hostname: web-01 Connecting to web-01...
Clear Prompts
Always end prompts with space or colon+space for readability:
# Good prompts
ip = input("Target IP: ")
port = input("Port number: ")
# Multiline prompt
prompt = "Enter the VLAN ID to configure.\n"
prompt += "VLAN: "
vlan = input(prompt)
Numerical Input
input() always returns strings. Convert for math:
>>> port = input("Port: ")
Port: 443
>>> port
'443' (1)
>>> port > 100 # TypeError - can't compare str to int
| 1 | String, not integer |
Use int() or float() to convert:
port = input("Port: ")
port = int(port) # now numeric
if port < 1024:
print("Privileged port - requires root")
Or convert inline:
port = int(input("Port: "))
The Modulo Operator
% returns the remainder of division:
10 % 3 # 1
15 % 5 # 0 (evenly divisible)
Common use - check if even/odd:
if port % 2 == 0:
print("Even port number")
While Loops
while runs as long as condition is true:
retries = 3
while retries > 0:
print(f"Attempting connection... ({retries} left)")
retries -= 1
Attempting connection... (3 left) Attempting connection... (2 left) Attempting connection... (1 left)
User-Controlled Loops
prompt = "\nEnter server to ping (or 'quit'): "
target = ""
while target != 'quit':
target = input(prompt)
if target != 'quit':
print(f"Pinging {target}...")
Using a Flag
For complex exit conditions, use a flag variable:
active = True
while active:
command = input("\nCommand: ")
if command == 'quit':
active = False
elif command == 'status':
print("All systems operational")
elif command == 'help':
print("Commands: status, quit, help")
The flag approach keeps the while line clean while handling multiple exit conditions.
break - Exit Immediately
break exits the loop instantly:
while True: # infinite loop
server = input("\nServer to check (q to quit): ")
if server == 'q':
break
print(f"Checking {server}...")
while True with break is a common pattern for "loop until user quits."
continue - Skip to Next Iteration
continue skips remaining code and restarts the loop:
port = 0
while port < 10:
port += 1
if port % 2 == 0:
continue # skip even ports
print(f"Checking port {port}")
Checking port 1 Checking port 3 Checking port 5 Checking port 7 Checking port 9
Avoiding Infinite Loops
Every while needs a way to become false:
# WRONG - infinite loop
x = 1
while x <= 5:
print(x)
# forgot x += 1
# RIGHT
x = 1
while x <= 5:
print(x)
x += 1
If stuck in infinite loop: Ctrl+C to interrupt.
While Loops with Lists
Don’t modify a list inside a for loop. Use while instead.
Moving Items Between Lists
pending = ['web-01', 'web-02', 'db-01']
deployed = []
while pending:
server = pending.pop()
print(f"Deploying {server}...")
deployed.append(server)
print(f"\nDeployed: {deployed}")
Deploying db-01... Deploying web-02... Deploying web-01... Deployed: ['db-01', 'web-02', 'web-01']
Removing All Instances of a Value
remove() only deletes first occurrence. Use while for all:
ports = [80, 443, 80, 8080, 80, 22]
while 80 in ports:
ports.remove(80)
print(ports) # [443, 8080, 22]
Filling a Dictionary
inventory = {}
polling = True
while polling:
hostname = input("\nHostname: ")
ip = input("IP address: ")
inventory[hostname] = ip
more = input("Add another? (yes/no) ")
if more == 'no':
polling = False
print("\n--- Inventory ---")
for host, ip in inventory.items():
print(f"{host}: {ip}")
Common Patterns
Menu Loop
while True:
print("\n1. Show status")
print("2. Run backup")
print("3. Exit")
choice = input("Select: ")
if choice == '1':
print("Status: OK")
elif choice == '2':
print("Running backup...")
elif choice == '3':
break
else:
print("Invalid choice")
Retry with Limit
max_attempts = 3
attempts = 0
success = False
while attempts < max_attempts and not success:
attempts += 1
print(f"Attempt {attempts}...")
# success = try_connection()
if not success:
print("Failed after max attempts")
Input Validation
while True:
port = input("Enter port (1-65535): ")
if not port.isdigit():
print("Must be a number")
continue
port = int(port)
if 1 <= port <= 65535:
break
print("Port out of range")
print(f"Using port {port}")
Quick Reference
| Pattern | Code |
|---|---|
Get input |
|
Convert to int |
|
While loop |
|
Infinite loop |
|
Exit loop |
|
Skip iteration |
|
Flag pattern |
|
Process list |
|
Exercises
7-1. Rental Car
Prompt for car type desired. Print confirmation message.
7-2. Port Scanner
Ask user for ports to scan. Print each port entered. Stop on 'quit'.
7-3. Server Inventory
Build a dictionary of server hostnames to IPs using a while loop.
7-4. Remove Service
Create a list with duplicate service names. Remove all instances of one service.
7-5. Three Ways to Exit
Write the same loop three ways:
- Conditional in while statement
- Using a flag variable
- Using break
Summary
-
input()returns strings - convert for numeric use -
whileloops run until condition becomes false -
breakexits immediately,continueskips to next iteration -
Use flags for complex exit conditions
-
Modify lists with
while, notfor -
while True+breakis a common pattern
Next: Functions for reusable code blocks.