How do I round this quiz percentage in python?

Viewed 21

I am a total python newb here. I am following the "5 Mini Python Projects" Quiz Game tutorial by Tech with Tim (finding it incredibly helpful), and one of the things I did was create a code to give someone a percentage after they take my quiz. The percentage ends up being with a lot of decimal places. How can I have 0 decimal places? I don't want to be that precise.

Here is some of my code including a quiz question:

answer = input("What's my favorite pizza? ")
if answer.lower() == "4 cheese":
    print("Correct! Nice job!")
    score += 1
else:
    print("Incorrect, sorry man!")

print("You got " + str(score) + " questions correct!")
print("You got " + str((score / 3) * 100) + "%.")

Some of the output is

"You got 33.33333333333333%."

I tried looking for answers to this, I know there's a round function but I have no idea how to use it, if anyone here could help. Thanks! Having fun so far with my 2nd week ever programming.

1 Answers

I'd say no reason to use round in your code as you only want to format the print statement. In your case I'd use:

print(f"You got {score / 3:.0%}")

Use f-Strings and .n% to allow n decimal places.

print(f"You got {score / 3:.2%}")  # print number with 2 decimal places.
Related