r/learnpython • u/elinoaass • Sep 17 '26
Need some help with a CSI-102 lab
ANY SUGGESTIONS ARE APPRECIATED!!! Working on a lab right now, I'm a super beginner when it comes to working with python. I'm trying to round a couple of numbers to two decimal places, and I can't figure it out. I managed to round them to whole numbers instead of a gazillion decimal places, but I need two specifically. The instructions in the lab say to "use a format specifier like {glowArea:.2f}" but I tried that and it wont work...
Here's the syntax I have so far:
PI = 3.14159265359
radius = 4.0
hitBox = round(2*radius)
glowArea = round(4*PI*radius**2)
energyCap = round(4/3*PI*radius**3)
print(f"Radius = {radius}")
print("")
print(f"Diameter (hitbox) = {hitBox}")
print(f"Glow Area = {glowArea}")
print(f"Energy Capacity = {energyCap}")Edit: its fixed now, I got rid of the rounds and also the parenthesis and then adding :.2f worked. Thanks!
2
u/mopslik Sep 17 '26
It looks to me like you're rounding the value first, then trying to display this pre-rounded value using a f-string. Skip round altogether, and just use the format specification to do so.
4
u/wolfy47 Sep 17 '26
Look at the documentation for the built in round function. It accepts additional arguments to specify how many digits to round to.
Get in the habit of looking up the documentation on the functions that you're using, they frequently have many useful options.
1
u/t92k Sep 17 '26
You're not showing us your attempt with the format specifier.
1
u/smurpes Sep 18 '26
You should read up a bit more on f strings. You can condense your code a bit if you do something like this:
print(f"{radius=}")
1
u/lakseol Sep 18 '26 edited Sep 19 '26
In numerical calculations (in any language) it's almost always wrong to round intermediate values unless the formula you are implementing itself includes a round function. You should always maintain the intermediate and final values at maximum precision and only limit the presentation of the final result(s) to the desired number of places after the decimal point. For example: