Just started a course and the exercise was to learn how to use round(x, n)
to truncate floats
.
Only problem is, it didn't. I found out about how to use %.1f
online, but is there a way to apply it to multiple variables instead having to write it over and over?
I have it set up like below:
a = float(input("a:"))
b = float(input("b:"))
c = float(input("c:"))
d = float(input("d:"))
e = float(input("e:"))
sum = a + b + c + d + e
average = sum/5
print ("The sum of ", "%.1f" % (a), ", ", "%.1f" % (b), ",", "%.1f" % (c), ", ", "%.1f" % (d), ", and ", "%.1f" % (e), "is ", "%.1f" % (sum), ". Meanwhile, the average is ", "%.2f" % (average), ".")
Is there a way to apply the %.1f
without having to write it so much?
edit: thanks to everyone that helped out. I found onur güngör's to have worked best with what I'm looking for, but I learned a lot more than what I needed from everyone's input. appreciate it.
I guess you want something like this.
n = 10
vars = []
for i = range(1, n+1):
vars.append(float(input("%d: " % i)))
vars_sum = sum(vars)
average = vars_sum/5
str = "The sum of "
for var in vars[:-1]:
str += "%.1f, " % var
str += "and " + "%.1f" % vars[-1:][0] + " is %.1f." % vars_sum
str += " Meanwhile, the average is %.2f." % average
print(str)