Getting "invalid syntax" from previously working code - python

So I have the following code:
f = open('input.txt', 'r')
text = f.read()
data = text.split()
print data
print '<HTML>\n <HEAD>\n </HEAD>\n <BODY>\n <table border="1">\n'
for x in data:
print ' <tr>' + x + '<tr>'
print'</table>\n </BODY>\n</HTML>'
before I tried to installed iPython, it was working with the default Python shell.
But after I installed distribute and pyreadline and then iPhython, the code won't stop giving me syntax errors, as if not a single variable would work, not sure if there is something about python initialization/declaration that I have missed or if something went wrong with doing stuff on the console, but it certainly is driving me crazy and I need to fix it.
P.S. I use Windows 8
Edit:
Was asked for the errors I get, here are screenshots, since I do not get any very specific text-like errors.
In this second one, I edited the code several times to test different things,
hence why I get error for different variables.
Even the simplest of things would give me an error.
P.S.2. I just tried print 'hey' and it gave me the same error, not recognizing the ' token.

Looks like whatever you installed is using Python 3.x, and your code was written for Python 2.x.
In Python 3.x, print is now a function, not a keyword, so you'll have to change all the lines like...
print data
...to...
print(data)
If you need to retain Python 2.x compatibility, add the line...
from __future__ import print_function
...at the top of the code.

Related

Previously working Python program reports in IndentationError when new variables are added

I'm getting "Indentation Error: Unexpected indent" in places I don't think I should be getting them in.
Here is my code for reference, along with a detailed explanation below:
for PID in PID_book:
print "\n##############################\nTEXT!\n##############################\n"
### COMMENT ###
print "\n##### AND MORE TEXT #####\n"
# Iterate through the lines and add valid data to the lists
gap_count = 0
hr_temp_total = 0
same_hr_count = 0
cur_dt = time.time()
first_run = True
# Keep track of the month for cool-looking progress bar
cur_month = 0
Above gap_count and cur_month are new variables I added. I get an indentation error at the the line with gap_count. If I remove that line, I still get the same error at the declaration of cur_month. So it seems like these new variables are causing problems which I don't understand because these issues don't occur with the older variables and I've entered them the same way with the same IDE.
I've removed all empty lines, and I've double checked to ensure this is LF newlines not CRLF.
This is python 2.7 running in a bash shell on CentOS. I am using ATOM to edit.
I've been struggling with the same error. I have properly indented django/python code. When I run python manage.py shell < my_script.py in bash, I get an IndentationError. The issue was because I used CRLF line endings (Windows). I switched to LF (Unix) and it solved the problem.
In the Atom editor you can toggle between the two using the menu at the bottom right (on mine it's the first item in the menu). Still looking for it in Sublime...

Not printing after if statment

So I have just started learning to use Python, and I am getting a syntax error.
Following the book I am using , here is a simple if statement, followed by a print statement that happens regardless of the if statement.
name = "Doug"
if name == 'Doug' :
print "Hello, Doug!"
print "How are you today?"
The expected output is:
Hello Doug!
How are you today?
if name != Doug, then the output should be
How are you today?
I've done simple ifs a thousand times in C++ and Java, but with brackets. For some reason, the final print comes back with a syntax error.
I am using Python 2.7.8, not Python 3, and using print or print() gives me the same result.
EDIT:
No amount of Newlines in the interpreter version worked, however running the script in a .py file worked flawlessly. For some reason , my book failed to mention this.
Your code works for me if I put it in a .py file and run the file through the interpreter. E.g. python hello.py. If I run the python interpreter interactively, however, then I can reproduce a syntax error at the second print statement.
I think this is just a quirk of interactive mode. I can make it work in interactive mode, too, by putting an extra newline between the two print statements. For what it's worth, the interactive-mode prompting makes me think that it doesn't recognize the end of the if statement until I type that extra newline after it (otherwise, another statement in the if block might follow).

Python 3.3: separation argument (sep) giving an error

I am very new to programming and I'm starting out with Python. I tried to look up my question here but didn't really find anything.
I'm trying to work a very simple print command but I'm getting an error for some reason that I don't understand.
last = 'smith'
middle = 'paul'
first = 'john'
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
According to the answer in the book, this should be right, but every time I try to run it, I get an error with the 'sep':
print(first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
^
SyntaxError: invalid syntax
Can someone tell me what I'm doing wrong. for what it's worth I'm using PyScripter.
[EDIT]
Thanks for that. I found out that I'm using Python 2.7.3 instead of 3.3. So I looked up the manual to see how the separator works. It seems to me that the only difference is with the square bracket. The manual describes the print function as :
print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout])
So I changed my print command and added the square bracket:
print ([first.capitalize(),middle.capitalize(),last.capitalize()] [, sep='\t'])
but unfortunately this doesn't work either as I get an error that highlights the square brackets around sep='\t'. Even when I take the brackets out, the error doesn't go away.
I'm not sure what I'm doing wrong, it seems like it should be very simple.
You aren't actually using Python 3, you just think you are. Try:
import sys
print(sys.version)
and see what comes out. The Python 2 print ... statement (not print(...) function in Python 3) interprets this as
print (first.capitalize(), middle.capitalize(), last.capitalize(), sep='\t')
which is trying to print a tuple with a keyword argument, thus the syntax error on sep

Python Help .Join giving syntax error

I have been learning Python on Codecademy.com and transferred a project that worked on the site (Battle Ship for those who used the site) and now I'm getting a syntax error with part of my code. On the site it runs smoothly.
The problem is when I take a list of strings and use join on them to display the game board.
result = " ".join(row)
print result
It is giving the error on the print result. On the site, the code was one line but I broke it down to see what was giving the error. Currently I have python 3.3 installed. Could something have changed between the version of Python interpreters that may have cause this?
In Python 3.x, print is a function, so try:
result = " ".join(row)
print(result)
you can use the following in python 2,
print "%s." %" ".join(row)
Alternatively, use the following in python 3,
print(*row, sep=' ')

Is it possible to access the source code of a python script passed to python on standard in?

This is a bit of a random question that is more out of curiosity than any specific need.
Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python code stored in a file? For example, doing something like this at the Bash prompt:
$ echo '
> print "The Code:"
> PrintScript() # What would this function look like?
> for i in range(5):
> print i,
> print "!"
> ' | python
and get an output like this:
The Code:
print "The Code:"
PrintScript() # What would this function look like?
for i in range(5):
print i,
print "!"
0 1 2 3 4 5 !
I suspect that this probably can't be done, but given python's introspection capabilities, I was curious to know whether it extended to this level.
That's the closest I'm getting:
echo 'import __main__,inspect;print inspect.getsource(__main__)' | python
which fails... In any case, the original code is eaten up (read from stdin) by the interpreter at startup. At most you may be able to get to the compiled code, again through the __main__ module.
Update:
The dis module is supposed to give you a disassembly of all functions in a module, but even that one isn't seeing any code:
$ echo -e 'import __main__,dis;print dis.dis(__main__)' | python
None
And even when I throw in a function:
$ echo -e "import __main__,dis;print dis.dis(__main__)\ndef x():\n pass" | python
None
Yes, it is indeed possible to write a program which outputs it's own source. You don't need even introspection for this tasks, you just need to be able to print computed strings (works with every language).
The technique is called Quine and here is a rather short example in Python:
quine = 'quine = %r\r\nprint quine %% quine'
print quine % quine
But quines aren't limited to such simple programs. They can do much more, for example printing their own source backwards and so on... :)
print open(__file__).read(),
This will work on UNIX systems I think, but I'm not sure about Windows. The trailing comma makes sure that the source code is printed exactly, without an extra trailing newline.
Just realized (based on the comments below) that this does not work if your source code comes from sys.stdin, which is exactly what you were asking for. In that case, you might take advantage of some of the ideas outlined on this page about quines (programs printing their own source codes) in Python, but none of the solutions would be a single function that just works. A language-independent discussion is here.
So, in short, no, I don't think this is possible with a single function if your source code comes from the standard input. There might be a possibility to access the interpreted form of your program as a Python code object and translate that back into source form, but the translated form will almost surely not match the original file contents exactly. (For instance, the comments and the shebang line would definitely be stripped away).
closest you can get is using readline to interrogate the command history if available from what i can see e.g. but i suspect this may not contain stuff piped into the session and would only work for interactive sessions anyway

Categories