Print a server's hostname and IP from variables
Problem statement
Store a server's hostname and IP address in two variables, hostname and ip. Then print one line in this exact format:
web-01 has IP 10.0.1.15
The message must be built from the variables, so changing a variable changes the output.
Examples
Example 1
Input: hostname = "web-01"
ip = "10.0.1.15"
Output: web-01 has IP 10.0.1.15
Hints
Approach
Optimal
A variable is a label you attach to a value with =, so hostname = "web-01" stores the text web-01 under the name hostname. Later lines can use that name instead of repeating the value. To combine variables and fixed text, use an f-string: put the letter f right before the opening quote, and write each variable inside curly braces {}. Python replaces {hostname} and {ip} with their current values when the line runs. This is the pattern you will use constantly for log messages and reports.
hostname = "web-01"ip = "10.0.1.15" print(f"{hostname} has IP {ip}")Follow-up questions
- Add a
portvariable and printweb-01 has IP 10.0.1.15 and listens on 443. - Print the same line using
print(hostname, "has IP", ip)and notice howprintadds spaces for you.
Frequently asked questions
Real scripts loop over many servers or read values from files. If the message uses variables, the same line works for every server without editing it.
You forgot the f before the opening quote. Without it, Python treats the braces as normal characters.