Terminal says "Syntax Error" when I try to open a file (Python)
As a short background, I am just starting to learn Python and am familiarizing myself with the whole environment.
Now, I have 3 things open (Windows Vista): Command Prompt, IDLE (Python GUI), and gedit.
On the IDLE, I started typing print commands like so:
>>> print "Print this."
Print this.
>>> run thisfile.py
SyntaxError: invalid syntax
>>> print "Hello world."
Hello world.
Then I saved this file as prac1.py. Now, I opened Command Prompt, went to the directory where this file is sa开发者_运维问答ved and typed:
C:\Python27\PythonProjects>prac1.py
But Command Prompt/Terminal displays:
File "C:\Python27\PythonProjects>prac1.py", line 1
Syntax error: invalid syntax
What am I doing wrong? I haven't typed anything on gedit yet.
You can't run another script like that.
You need to import it, and then you can call functions and use types in it, like this:
import thisfile
This will import the contents of thisfile into the interpreter, then you can call functions:
thisfile.thatfunction
If you want "thatfunction" to be available without prefixing it with "thisfile", import the contents instead:
from thisfile import *
In any case, there is no run
command, so wherever you got that from is not a good place to learn Python from.
Not everything you see in the interactive shell is valid Python code.
Skip the >>>
prompt and output in a Python file. For example try to run this:
print "Print this."
run thisfile.py
print "Hello world."
Though, this still won't work because of other problems. I am leaving that to you to solve. Have fun!
Thanks for the answers but just now, I figured out what's wrong. I should type in the commands inside gedit (editor) and not inside IDLE. But I'll also try other ways to run the file like what you guys suggested. ;)
精彩评论