#Rounding up function
1 messages · Page 1 of 1 (latest)
;compile
import math
x = 5/3
y = round(x, 2)
print(f"X: {x}")
print(f"Y: {y}")
# You can also use string formating
print(f"f-string: {x:.2f}") # prefered
print("format: {:.2f}".format(x))
print(f"old style: %.2f"% x)
Program Output
X: 1.6666666666666667
Y: 1.67
f-string: 1.67
format: 1.67
old style: 1.67
Malassi#0410 | 272ms | python | Python 3.10 | godbolt.org
Btw, you should always space your imports from your code it increase readability which makes your code easier to read, write and debug.
Your call to math.pi on line 2 doesn't do anything.
oh
Thank you so much.
I want to add to this that always write your code in a function, even if it’s a small practice code like this one, I am a believer of good habit early in your career instead of trying to undo bad habit late in your career. It will help readability and as well as catching some error.
Here's a good base python layout
# imports
# constants
# function/class
# Python's version of a main function
if __name__ == '__main__':
# main code here
;compile
from math import sqrt
def hypotenuses(a: float, b: float) -> float:
return sqrt(a**2 + b**2)
if __name__ == '__main__':
a = 5
b = 10
c = hypotenuses(a, b)
print(f"{a}^2 + {b}^2 = {c:.2f}")
Program Output
5^2 + 10^2 = 11.18
Malassi#0410 | 113ms | python | Python 3.10 | godbolt.org
Concrete exemple