'Printing Decimals as Percentages
I'm new to coding and I don't know how to translate a list of decimals into percentages using a for loop. This is what I have and this is the error I get.
Create a list named q_growth_rates using list comprehension (preferred) or a for loop
Print each growth rate as shown below using a for loop
q_growth_rates = []
q_growth_rates = [-0.2, -0.1, 0.0, 0.09999999999999998, 0.2]
print(q_growth_rates)
I get an error code that says "TypeError: unsupported format string passed to list.format" for the following
You need to use f-strings for formatting
Make sure that all decimals are aligned as shown below and there is a percent sign at the end
growth = [ str(round(x*100,1))+"%" for x in q_growth_rates]
print(f"{growth= :6,.2}")
the answer is given as the following, but I have to code the step before.
growth=-20.00%
growth=-10.00%
growth= 0.00%
growth= 10.00%
growth= 20.00%
Solution 1:[1]
This should work:
q_growth_rates = []
q_growth_rates = [-0.2, -0.1, 0.0, 0.09999999999999998, 0.2]
print(q_growth_rates)
growth = [ str(round(x*100,1))+"%" for x in q_growth_rates]
for i in growth:
print(f"growth={i}")
Output:
[-0.2, -0.1, 0.0, 0.09999999999999998, 0.2]
growth=-20.0%
growth=-10.0%
growth=0.0%
growth=10.0%
growth=20.0%
You forgot the close your string on the print statement and you need to loop through the growth list to print everything in it like you specified.
Or you could try:
q_growth_rates = []
q_growth_rates = [-0.2, -0.1, 0.0, 0.09999999999999998, 0.2]
print(q_growth_rates)
growth = [ str(round(x*100,1))+"%" for x in q_growth_rates]
print("\n".join(f"growth={i}" for i in growth))
Output:
[-0.2, -0.1, 0.0, 0.09999999999999998, 0.2]
growth=-20.0%
growth=-10.0%
growth=0.0%
growth=10.0%
growth=20.0%
Solution 2:[2]
You can just print the growth directly in the list comprehension
q_growth_rates = [-0.2, -0.1, 0.0, 0.09999999999999998, 0.2]
[print(f'growth = {round(x*100,1)}%') for x in q_growth_rates]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | catasaurus |
| Solution 2 | BiRD |
