0

I use Python2.7 on win10 64bit to raise a function. The code is following:

def test_stationarity(timeseries):

    #Determing rolling statistics
    rolmean = timeseries.rolling(window = 12,center = False).mean()
    rolstd = timeseries.rolling(window = 12,center = False).std()

    #Plot rolling statistics:
    orig = plt.plot(timeseries, color='blue',label='Original')
    mean = plt.plot(rolmean, color='red', label='Rolling Mean')
    std = plt.plot(rolstd, color='black', label = 'Rolling Std')
    plt.legend(loc='best')
    plt.title('Rolling Mean & Standard Deviation')
    plt.show(block=False)

    #Perform Dickey-Fuller test:
    print 'Results of Dickey-Fuller Test:'
    dftest = adfuller(timeseries, autolag='AIC')
    dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
    for key,value in dftest[4].items():
        dfoutput['Critical Value (%s)' % key] = value
    print dfoutput

when I run this function:

File "<ipython-input-20-ff069253bfd6>", line 17
    print 'Results of Dickey-Fuller Test:'
                                         ^
SyntaxError: invalid syntax

Why does this error happen?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Chunk_Ning
  • 113
  • 2
  • 8
  • 4
    Start by actually using Python 2. This is an error thrown by Python 3 by accident.. – Martijn Pieters Apr 23 '17 at 14:21
  • Of Couse! I certainly use Python2 Jupyter Notebook – Chunk_Ning Apr 23 '17 at 14:24
  • Both Python 2 and Python 3 support the syntax `print('String')`, so whether you're using python 2 or 3, use `print` as a function, rather than a statement. – Robert Seaman Apr 23 '17 at 14:25
  • 1
    @RobertSeaman: That `print('string')` works in Python 2 is a coincidence, not by design; the parser still treats that as `print 'string'`. The moment that you try to treat `print()` as a function and try to pass in more arguments, that starts to break down (suddenly you are printing tuples). Better to then go the whole hog and use `from __future__ import print_function` at the top in that case. But the OP is probably *not* trying to write polyglot code here. – Martijn Pieters Apr 23 '17 at 14:28
  • Robert!Thanks a lot! I just change it to print ('string'),and the problem is solved!Thank you! – Chunk_Ning Apr 23 '17 at 14:32
  • I'm glad that worked. And thank you @MartijnPieters for the full explanation. – Robert Seaman Apr 23 '17 at 14:36

0 Answers0