-1

I have made a math game that gives a percentage at the end of questions you got right.

I don't want any zeros I just want it to round to the nearest whole number. I don't know who to do this though.

This is the code that makes the percentage:

percentage = correct / questions * 100
print ("Your Correct Percentage: ", percentage, "%")

And the result when you get 1/3 right is:

Your Correct Percentage:  33.33333333333333 %

I want the 33.3333333333 to just round down to 33. Thank You, Andrew the Python Coder

2 Answers2

2

You can use the standard function round:

percentage = correct / questions * 100
print ("Your Correct Percentage: ", round(percentage), "%")

It also accepts a second parameter that specifies the number of decimal places to round to. For instance, if you wanted a bit more precision, say, two decimal places, use:

print ("Your Correct Percentage: ", round(percentage, 2), "%")
iz_
  • 15,923
  • 3
  • 25
  • 40
1

You could str.format (doc) to do it for you:

correct, questions = 1, 3
percentage = correct / questions * 100
print ("Your Correct Percentage: {:.2g}%".format(percentage))
#OR:
#print ("Your Correct Percentage: {:.0f}%".format(percentage))

Prints:

Your Correct Percentage: 33%

OR to add % sign automatically, without any digits after .:

correct, questions = 1, 3
print ("Your Correct Percentage: {:.0%}".format(correct / questions))
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91