15,391,989 members
See more:
Python
1  from decimal import Decimal, getcontext
2  import math
3  def calc(n):
4      t = Decimal(0)
5      pi = Decimal(0)
6      deno = Decimal(0)
7      k = 0
8      for k in range(n):
9          t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409+545140134*k)
10          deno = math.factorial(3*k)*(math.factorial(k)**Decimal(3))*(640320**(3*k))
11          pi += Decimal(t)/Decimal(deno)
12      pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
13      pi = 1/pi
14      return str(pi)
15  print(calc(1))

What I have tried:

Hi I am completley new to coding and learning python using the black dog python manual. I've copied the code from the book and cant see why im having an issue getting the code to run. SyntaxError: invalid syntax (<string>, line 14)
Posted
Updated 17-May-20 8:59am
v5
[no name] 17-May-20 11:07am

When I run this on https://www.tutorialspoint.com/execute_python_online.php[^] it compiles and runs...
essexcase 17-May-20 11:20am

ive just tried through the same website and still get the same syntaxError?
[no name] 17-May-20 11:31am

Strange, for me it prints a number that looks like pi...

Ok, after copy/paste I need to adjust two line break, but that is simply a formatting issue.

I formatted a liitle bit your code and now I can copy/paste it to the link above and it runs without any additional modifications.
essexcase 17-May-20 11:47am

Thank you, it now runs on tutorialspoint, but when i try and run the same code in my shell i get this message

Traceback (most recent call last):
File "C:\python\picalc.py", line 16, in <module>
print(calc(1))
File "C:\python\picalc.py", line 10, in calc
t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409+545140134*k)
TypeError: 'decimal.Decimal' object cannot be interpreted as an integer
>>>
[no name] 17-May-20 11:54am

Sorry, I don't know Python... but I guess
Decimal(13591409+545140134*k)
and
Decimal(640320**(3*k))
maybe helps.

Here Repl.it - Python Online Compiler and IDE - Fast, Powerful, Free[^] I get same error like you.

After removing Decimal conversion here
t = (Decimal(-1)**k)*(math.factorial(6*k))*(13591409+545140134*k)
t = (Decimal(-1)**k)*(math.factorial(Decimal(6)*k))*(13591409+545140134*k) it runs
essexcase 17-May-20 14:42pm

Thank you.

## Solution 2

Python
1  from decimal import Decimal, getcontext
2  import math
3  def calc(n):
4      t = Decimal(0)
5      pi = Decimal(0)
6      deno = Decimal(0)
7      k = 0
8      for k in range(n):
9          t = (Decimal(-1)**k)*(math.factorial(6*k))*(13591409+545140134*k)
10          deno = math.factorial(3*k)*(math.factorial(k)**Decimal(3))*(640320**(3*k))
11          pi += Decimal(t)/Decimal(deno)
12      pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
13      pi = 1/pi
14      return str(pi)
15  print(calc(1))

It looks like some python implementations do implicit type conversions while other do not.
Sorry that I can't give more trustfull information.
v2