Build hostnames with a default environment
Problem statement
Write a function make_hostname(role, number, env="prod") that returns a hostname like prod-web-03. The number is always shown with two digits. If env is not given, it defaults to "prod". Print the result of the two calls in the examples.
Examples
Example 1
Input: make_hostname("web", 3)
Output: prod-web-03
Example 2
Input: make_hostname("db", 12, "staging")
Output: staging-db-12
Hints
Approach
Optimal
Parameters can have default values, written as env="prod" in the def line. If the caller leaves that argument out, the default is used; if they pass a value, it replaces the default. Parameters with defaults must come after those without. To pad the number, use a format specifier inside the f-string: {number:02d} means "show as a whole number, at least 2 characters wide, padded with zeros". The function returns the finished string so the caller can print it or use it elsewhere.
def make_hostname(role, number, env="prod"): return f"{env}-{role}-{number:02d}" print(make_hostname("web", 3))print(make_hostname("db", 12, "staging"))Follow-up questions
- Use the function in a loop to print
prod-web-01throughprod-web-05.
Frequently asked questions
Yes: make_hostname("db", 12, env="staging") works and makes the call clearer, especially when a function has several optional parameters.