5

Here is my code. I need to add a percent symbol at the end of the print string. I can't get this figured out.

total = 0
counter = 0
while True:
    score = int(input('Enter test score: '))
    if score == 0:
        break
    total += score
    counter += 1
average = total / counter
print('The average is:', format(average, ',.3f'))
Casimir Crystal
  • 18,651
  • 14
  • 55
  • 76
spbiknut
  • 75
  • 5
  • What does `format` do? – Peter Wood Nov 07 '15 at 23:50
  • Possible duplicate? http://stackoverflow.com/questions/10678229/how-can-i-selectively-escape-percent-in-python-strings – Pierre L Nov 07 '15 at 23:58
  • @PeterWood It’s a [built-in function](https://docs.python.org/3/library/functions.html#format). – poke Nov 08 '15 at 00:02
  • @PierreLafortune No, this question doesn’t use percent-formatting. – poke Nov 08 '15 at 00:03
  • I agree. There may be a dupe though. The upvoted answer here is only workaround. It doesn't answer the direct question of escaping the percent operator. – Pierre L Nov 08 '15 at 00:04
  • @PierreLafortune I think you are overinterpreting this question; there was never a need to escape the percent *symbol*. The second argument to `format` is only for the format specification, characters that should be displayed in the output would never belong there, so you wouldn’t have to escape anything. The unfortunately downvoted answer perfectly explains how to add a percent character at the end of the printed string, as OP is asking for. – poke Nov 08 '15 at 00:08
  • @poke tough crowd maybe. I upvoted the answer, maybe it can get more attention. – Pierre L Nov 08 '15 at 00:11
  • @poke I have never noticed that before! Thanks – Peter Wood Nov 08 '15 at 09:31

2 Answers2

6

The probably best way would be to just use the percent format type:

format(average, '.1%')

# or using string formatting:
'{:.1%}'.format(average)

This already multiplies the average by 100 and will also show a percent sign at the end.

>>> average = .123
>>> print('The average is: {:.1%}'.format(average))
The average is: 12.3%
poke
  • 307,619
  • 61
  • 472
  • 533
4
print('The average is: ' + format(average, ',.3f') + '%')

?

poke
  • 307,619
  • 61
  • 472
  • 533
Stephane Martin
  • 1,576
  • 1
  • 15
  • 25