+ 1

Why is rounding necessary to just get a result here?

This is the code provided in the text analyzer section: def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count filename = input("Enter a filename: ") with open(filename) as f: text = f.read() for char in "abcdefghijklmnopqrstuvwxyz": perc = 100 * count_char(text, char) / len(text) print("{0} - {1}%".format(char, round(perc, 2))) So, I understand that round(perc, 2) is supposed to round the result to 2 decimals. What I don't understand is why simply deleting this part will not work. When I use this line of code: print("{0} - {1}%".format(char)) I will receive an IndexError while I would be expecting to just receive an unrounded result. Can anyone more experienced elaborate?

26th Dec 2016, 9:52 AM
Alpha
1 Réponse
+ 1
Your code doesn't work anymore because you deleted the whole information of the place holder. in the original, {0} refers to the variable char and {1} to round(perc,2), which is the variable perc rounded to 2 decimals. {1} doesn't have any content of you delete round(perc,2). To have the result without rounding it, write format(char, perc).
26th Dec 2016, 3:04 PM
Sophia