문제

This is not my code it is example code from this website: https://github.com/karan/Projects/blob/master/Numbers/pi.py

# Find PI to the Nth Digit

from math import *

digits = raw_input('Enter number of digits to round PI to: ')

# print ('{0:.%df}' % min(20, int(digits))).format(math.pi) # nested string formatting

# calculate pi using Machin-like Formula
print ('{0:.%df}' % min(30, int(digits))).format(4 * (4 * atan(1.0/5.0) - atan(1.0/239.0)))

When I run it I get this error

Traceback (most recent call last):
  File "C:/Python34/pi.py", line 7, in <module>
    print ('{0:.%df}' % min(30, int(num))).format(4 * (4 * atan(1.0/5.0) - atan(1.0/239.0)))
AttributeError: 'NoneType' object has no attribute 'format'

Is this possibly a problem with the version of python I am using (3.4.0) Perhaps it is not compatible with this old code?

도움이 되었습니까?

해결책

Yes it is a problem with your python version. Add an external pair of parenthesis:

print(
    ('{0:.%df}' % min(30, int(digits))).format(4 * (4 * atan(1.0/5.0) - atan(1.0/239.0)))
 )

This is because in python3 print is a function and that expression is parsed as:

(print('{0:.%df}' % min(30, int(digits)))).format(...)

In other words print gets a single argument which is:

'{0:.%df}' % min(30, int(digits))

and the .format is called on the return value of the print call which is always None.

In python2, where print is a statement, everything is passed as an argument to the statement and thus the outer parenthesis aren't required.


Side note: you can avoid using the % formatting, since you can nest the formattings:

print('{0:.{1}f}'.format(4 * (4 * atan(1.0/5.0) - atan(1.0/239.0)), min(30, int(digits))))

Or maybe better:

print('{value:.{prec}f}'.format(prec=min(30, int(digits)), value=4 * (4 * atan(1.0/5.0) - atan(1.0/239.0))))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top