In previous examples
(e.g.,
Do
and
Environment variables),
all the values in the
dict
ionary
belonged to the same data type
(str
ing).
In this example, the values belong to different types.
As usual, however, all the keys are still
str
ings.
age citizenship favorite years leaning name zipcode What attribute do you want to see (e.g., name)? name The attribute name is Mark. age citizenship favorite years leaning name zipcode What attribute do you want to see (e.g., name)? age The attribute age is 64.25. age citizenship favorite years leaning name zipcode What attribute do you want to see (e.g., name)? favorite years The attribute favorite years is (1968, 2001, 2019). age citizenship favorite years leaning name zipcode What attribute do you want to see (e.g., name)?
str
ing,
print quotes around it.
Change
lines
28–31
to one of the following.
Which one is easier to understand?
I like the second one
because it cleanly separates the two jobs of
try
and the matching
except
as close together as possible.
try: value = attributes[key] if isinstance(value, str): print(f'The attribute {key} is "{value}".') else: print(f'The attribute {key} is {value}.') except KeyError: print(f'Sorry, "{key}" is not an attribute.')
try: value = attributes[key] except KeyError: print(f'Sorry, "{key}" is not an attribute.') else: #Arrive here if no exception was raised. if isinstance(value, str): print(f'The attribute {key} is "{value]}".') else: print(f'The attribute {key} is {value}.')
age citizenship favorite years leaning name zipcode What attribute do you want to see (e.g., name)? name The attribute name is "Mark". age citizenship favorite years leaning name zipcode What attribute do you want to see (e.g., name)? zipcode The attribute zipcode is 10003. etc.
float
,
print it with one digit to the right of the decimal point.