Python Forum
Odd interpreter behavior
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Odd interpreter behavior
#1
Im posting this in Homework as I am taking a self paced course.

Im on a Centos 6 vm.
There is both python 2.7.5 and 3.7 loaded.
I am not sure why I am getting the error given below.
Post preview shows that the alignment is incorrect.
The output = f.read() is lined up with the o in open
The print statement is lined up with the w in the with.


@localhost ~]$ python3.7
Python 3.7.4 (default, Jan  8 2020, 08:43:10) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("shver.txt") as f:
...      output = f.read()
... print(output)
  File "<stdin>", line 3
    print(output)
        ^
SyntaxError: invalid syntax
>>> 
Any help would be appreciated.

Thanks
Sum
Reply
#2
output = f.read() should be indented one level.
the print function may be inside the context manager or out:
>>> with open("shver.txt") as f:
...     output = f.read()
...     print(output)
>>> with open("shver.txt") as f:
...     output = f.read()
>>> print(output)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Thanks ..

it is actually .. for some reason the forum interface doesnt like the paste of the resulting error.
Reply
#4
Actually it would be

>>> with open("shver.txt") as f:
...     output = f.read()
...
>>> print(output)
i.e. you need to exit the context manager by entering blank line
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
yes. Thank you.

I played around last night and found that, yes, the print should be outside of the existing block.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020