Print pi to a number of decimal places

Fraser  picture Fraser · Jul 31, 2017 · Viewed 31.2k times · Source

One of the challenges on w3resources is to print pi to 'n' decimal places. Here is my code:

from math import pi

fraser = str(pi)

length_of_pi = []

number_of_places = raw_input("Enter the number of decimal places you want to 
see: ")

for number_of_places in fraser:
    length_of_pi.append(str(number_of_places))

print "".join(length_of_pi)

For whatever reason, it automatically prints pi without taking into account of any inputs. Any help would be great :)

Answer

Moses Koledoye picture Moses Koledoye · Jul 31, 2017

Why not just format using number_of_places:

''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'

And more generally:

>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'

In your original approach, I guess you're trying to pick a number of digits using number_of_places as the control variable of the loop, which is quite hacky but does not work in your case because the initial number_of_digits entered by the user is never used. It is instead being replaced by the iteratee values from the pi string.