Setting number of decimals for print via user input

Viewed 37

I'm dabbling around in Python and wrote a short program which returns the square root of a number provided by the user. The output, respectively the print line, looks like this:

print 'The square root of %d is %.2f' % (x, math.sqrt(x))

with x as the user input.

My question: how could i adjust the results number of decimals via user input?

Thanks a lot!

1 Answers

First get input for how many decimal places you want it by:

y = int(raw_input("How many decimal places? "))

Then you'll probably want to use str.format to make your print statement easier:

print 'The square root of {} is {:.{dec}f}'.format(x, math.sqrt(x), dec=y)

I might be (I probably am) wrong here, but I'm not sure if you can do what you're trying to achieve with the % operator. % tends to be looked at as a deprecated operator anyway, especially with the majority of people transitioning to Python 3. But, since you're using Python 2, thankfully str.format is in Python 2.7.

Related