Print pi to a number of decimal places

前端 未结 7 2481
感情败类
感情败类 2020-12-19 08:56

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 = []

numbe         


        
7条回答
  •  悲&欢浪女
    2020-12-19 09:29

    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.

提交回复
热议问题