Print a port availability grid for a list of hosts
Problem statement
This looks like the last problem, a nested loop over two lists, but with one real difference: instead of printing every combination as-is, each cell needs to look something up first, is this specific port actually open on this specific host, and print open or closed based on the answer. A nested loop alone isn't enough here, it needs a check inside it too.
Common mistake: checking the host and the port separately instead of together.
Wrong:if host in open_connections and port in open_connections:This checks "does this host appear anywhere in the open list" and "does this port appear anywhere in the open list," separately, not whether this exact host-and-port pair is open together. A host open on port 80 would incorrectly show as open on port 443 too, as long as 443 was open on some other host. The check needs to be against the combined pair, not each part alone.
Your task: given hosts = ["host-a", "host-b"], ports = [80, 443], and a list of open combinations ["host-a:80", "host-a:443", "host-b:443"], print each host-port pair followed by open or closed.
Expected output:
host-a:80 openhost-a:443 openhost-b:80 closedhost-b:443 openApproach
For each host-port pair, build the same "host:port" text used in the open-connections list, then check whether that exact combined key appears in it.
Note: checking a list this way looks at items one by one, so it gets slower as the list grows. That's fine for a handful of connections. Later, in the Dictionaries section, you'll learn a faster way to do this same lookup.
hosts = ["host-a", "host-b"]
ports = [80, 443]
open_connections = ["host-a:80", "host-a:443", "host-b:443"]
for host in hosts:
for port in ports:
key = f"{host}:{port}"
status = "open" if key in open_connections else "closed"
print(f"{key} {status}")