samedi 18 juin 2016

Python interactive interpreter has problems with blank lines when I paste in a script

I'm an experienced programmer getting started with Python. I've written a simple Python script that I've placed into a file called add_function.py:

def myadd(a, b):

    sum = a + b
    return sum

result = myadd(10, 15)
print result

Now, when I source the file from the Python interactive interpreter, it works fine:

% python
Python 2.7.5 (default, Sep 12 2013, 21:33:34) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("add_function.py")
25

However, when copy the script and then paste it directly into the interpreter, it seems that the interpreter cannot parse the blank lines. I find this frustrating because other scripting languages (e.g. R) do not distinguish between blank lines in a script and blank lines at the interactive prompt.

>>> def myadd(a, b):
... 
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block
>>>     sum = a + b
  File "<stdin>", line 1
    sum = a + b
    ^
IndentationError: unexpected indent
>>>     return sum
  File "<stdin>", line 1
    return sum
    ^
IndentationError: unexpected indent
>>> 
>>> result = myadd(10, 15)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'myadd' is not defined
>>> print result
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'result' is not defined

How do I fix this problem? I want to be able to paste in and try out code that I find on websites, and many of them have blank lines.

Aucun commentaire:

Enregistrer un commentaire