I am very new to python, this is my first program that I am trying.
This function reads the password from the standard input.
def getPassword() :
passwordArray =[]
while 1:
char = sys.stdin.read(1)
if char == '\\n':
break
passwordArray.append(char)
return passwordArray
print (username)
print (URL)
getting this error:
Problem invoking WLST - Traceback (innermost last):
(no code object) at line 0
File "/scratch/aime/work/stmp/wlstCommand.py", line 10
while 1:
^
SyntaxError: invalid syntax
Your indentation is not correct. Your while should be indented the same as the line above it.
Python uses indentation to "separate" stuff and the thing with that is you need to have the same kind of indentation across the file. Having a fixed kind of indentation in the code you write is good practice. You might want to consider a tab or four spaces(The later being the suggestion in the PEP8 style guide)
Python is sensitive and depended on indentation. If it complains "invalid Format", that is better than "invalid syntax".
Related
My question concern the code that was posted in this question Questions about a tic-tac-toe program I am writing.
More precisely this line:
stop = int(0)# 0 = continue
First I didn't understand what he was trying to do and thought that it was a SyntaxError. But when I tried to execute this line, it didn't raise a SyntaxError, it just set stop to 0. Note this line is not inside a loop.
>>> stop = int(0)# 0 = continue
>>> stop
0
But this, as I expected, raise a error:
>>> int(0) = continue
File "<stdin>", line 1
int(0) = continue
^
SyntaxError: invalid syntax
Do someone know why that line is valied, thanx.
# introduces a comment. Everything after it is a comment and has no meaning to the Python interpreter. The comment is likely trying to say "zero means to continue".
PEP8 advises that "inline comments should be separated by at least two spaces from the statement", which would probably have removed some confusion here.
print("inventory[", start,":", finish, "] is", end=" ")
This line of code has my program stuck. It didn't like the spacing so I eliminated it and now it is flagging the colon as invalid syntax. It is straight from my textbook and is a lesson about slicing lists. What am I missing?
For me this code works perfectly if start and finish have been defined.
This error can originate from a SyntaxError in the line before the print. Most certainly you are missing a parens or a bracket.
As an example consider the following code:
print(42 # closing parens intentinally missing here
print(23)
When executed this raises the following error:
File "foo.py", line 2
print(23)
^
SyntaxError: invalid syntax
As you can see the SyntaxError shows one line after the actual error. I suggest you check the line before your print statement.
It is very similar to this:
How to tell if a string contains valid Python code
The only difference being instead of the entire program being given altogether, I am interested in a single line of code at a time.
Formally, we say a line of python is "syntactically valid" if there exists any syntactically valid python program that uses that particular line.
For instance, I would like to identify these as syntactically valid lines:
for i in range(10):
x = 1
Because one can use these lines in some syntactically valid python programs.
I would like to identify these lines as syntactically invalid lines:
for j in range(10 in range(10(
x =++-+ 1+-
Because no syntactically correct python programs could ever use these lines
The check does not need to be too strict, it just need to be good enough to filter out obviously bogus statements (like the ones shown above). The line is given as a string, of course.
This uses codeop.compile_command to attempt to compile the code. This is the same logic that the code module does to determine whether to ask for another line or immediately fail with a syntax error.
import codeop
def is_valid_code(line):
try:
codeop.compile_command(line)
except SyntaxError:
return False
else:
return True
It can be used as follows:
>>> is_valid_code('for i in range(10):')
True
>>> is_valid_code('')
True
>>> is_valid_code('x = 1')
True
>>> is_valid_code('for j in range(10 in range(10(')
True
>>> is_valid_code('x = ++-+ 1+-')
False
I'm sure at this point, you're saying "what gives? for j in range(10 in range(10( was supposed to be invalid!" The problem with this line is that 10() is technically syntactically valid, at least according to the Python interpreter. In the REPL, you get this:
>>> 10()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
10()
TypeError: 'int' object is not callable
Notice how this is a TypeError, not a SyntaxError. ast.parse says it is valid as well, and just treats it as a call with the function being an ast.Num.
These kinds of things can't easily be caught until they actually run.
If some kind of monster managed to modify the value of the cached 10 value (which would technically be possible), you might be able to do 10(). It's still allowed by the syntax.
What about the unbalanced parentheses? This fits the same bill as for i in range(10):. This line is invalid on its own, but may be the first line in a multi-line expression. For example, see the following:
>>> is_valid_code('if x ==')
False
>>> is_valid_code('if (x ==')
True
The second line is True because the expression could continue like this:
if (x ==
3):
print('x is 3!')
and the expression would be complete. In fact, codeop.compile_command distinguishes between these different situations by returning a code object if it's a valid self-contained line, None if the line is expected to continue for a full expression, and throwing a SyntaxError on an invalid line.
However, you can also get into a much more complicated problem than initially stated. For example, consider the line ). If it's the start of the module, or the previous line is {, then it's invalid. However, if the previous line is (1,2,, it's completely valid.
The solution given here will work if you only work forward, and append previous lines as context, which is what the code module does for an interactive session. Creating something that can always accurately identify whether a single line could possibly exist in a Python file without considering surrounding lines is going to be extremely difficult, as the Python grammar interacts with newlines in non-trivial ways. This answer responds with whether a given line could be at the beginning of a module and continue on to the next line without failing.
It would be better to identify what the purpose of recognizing single lines is and solve that problem in a different way than trying to solve this for every case.
I am just suggesting, not sure if going to work... But maybe something with exec and try-except?
code_line += "\n" + ("\t" if code_line[-1] == ":" else "") + "pass"
try:
exec code_line
except SyntaxError:
print "Oops! Wrong syntax..."
except:
print "Syntax all right"
else:
print "Syntax all right"
Simple lines should cause an appropriate answer
Quick python question about the exec command. I'm have Python 2.7.6 and am trying to make use of the exec to run some code stored in a .txt file. I've run into a syntax error and am not entirely sure what is causing it.
Traceback (most recent call last):
File "/Users/XYZ/Desktop/parser.py", line 46, in <module>
try_code(block)
File "<string>", line 1
x = 'Hello World!'
^
SyntaxError: invalid syntax
I initially thought it was complaining about carriage returns, but when I tried to edit them .replace them with ' ' I still received this error message. I've tried variations to see what appears to be the issue and it always declares the error as the first ' or " the program encounters when it runs exec.
Here is the try_code(block) method
def try_code(block):
exec block
And the main body of the program
inputFile = open('/Users/XYZ/Desktop/test.txt', 'r+')
starter = False
finished = False
check = 1
block = ""
for val in inputFile:
starter = lookForStart(val)
finished = lookForEnd(val)
if lookForStart:
check = 1
elif finished:
try_code(block)
if check == 1:
check = 0
elif finished == False:
block = block + val
Basically I'm trying to import a file (test.txt) and then look for some embedded code in it. To make it easier I surrounded it with indicators, thus starter and finished. Then I concatenate all the hidden code into one string and call try_code on it. Then try_code attempts to execute it (it does make it there, check with print statements) and fails with the Syntax error.
As a note it works fine if I have hidden something like...
x = 5
print x
so whatever the problem is appears to be dealing with strings for some reason.
EDIT
It would appear that textedit includes some extra characters that aren't displayed normally. I rewrote the test file in a different text editor (text wrangler) and it would seem that the characters have disappeared. Thank you all very much for helping me solve my problem, I appreciate it.
It is a character encoding issue. Unless you've explicitly declared character encoding of your Python source code at the top of the file; it is 'ascii' by default on Python 2.
The code that you're trying to execute contains non-ascii quotes:
>>> print b'\xe2\x80\x98Hello World\xe2\x80\x99'.decode('utf-8')
‘Hello World’
To fix it; use ordinary single quotes instead: 'Hello World'.
You can check that block doesn't contain non-ascii characters using decode method: block.decode('ascii') it raises an exception if there are.
A gentle introduction into the topic: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
by Joel Spolsky.
This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 26 days ago.
if len(trashed_files) == 0 :
print "No files trashed from current dir ('%s')" % os.path.realpath(os.curdir)
else :
index=raw_input("What file to restore [0..%d]: " % (len(trashed_files)-1))
if index == "*" :
for tfile in trashed_files :
try:
tfile.restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
elif index == "" :
print "Exiting"
else :
index = int(index)
try:
trashed_files[index].restore()
except IOError, e:
import sys
print >> sys.stderr, str(e)
sys.exit(1)
I am getting:
elif index == "" :
^
IndentationError: expected an indented block
As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.
There are in fact multiples things you need to know about indentation in Python:
Python really cares about indention.
In a lot of other languages the indention is not necessary but improves readability. In Python indentation replaces the keyword begin / end or { } and is therefore necessary.
This is verified before the execution of the code, therefore even if the code with the indentation error is never reached, it won't work.
There are different indention errors and you reading them helps a lot:
1. "IndentationError: expected an indented block"
They are two main reasons why you could have such an error:
- You have a ":" without an indented block behind.
Here are two examples:
Example 1, no indented block:
Input:
if 3 != 4:
print("usual")
else:
Output:
File "<stdin>", line 4
^
IndentationError: expected an indented block
The output states that you need to have an indented block on line 4, after the else: statement
Example 2, unindented block:
Input:
if 3 != 4:
print("usual")
Output
File "<stdin>", line 2
print("usual")
^
IndentationError: expected an indented block
The output states that you need to have an indented block line 2, after the if 3 != 4: statement
- You are using Python2.x and have a mix of tabs and spaces:
Input
def foo():
if 1:
print 1
Please note that before if, there is a tab, and before print there is 8 spaces.
Output:
File "<stdin>", line 3
print 1
^
IndentationError: expected an indented block
It's quite hard to understand what is happening here, it seems that there is an indent block... But as I said, I've used tabs and spaces, and you should never do that.
You can get some info here.
Remove all tabs and replaces them by four spaces.
And configure your editor to do that automatically.
2. "IndentationError: unexpected indent"
It is important to indent blocks, but only blocks that should be indent.
So basically this error says:
- You have an indented block without a ":" before it.
Example:
Input:
a = 3
a += 3
Output:
File "<stdin>", line 2
a += 3
^
IndentationError: unexpected indent
The output states that he wasn't expecting an indent block line 2, then you should remove it.
3. "TabError: inconsistent use of tabs and spaces in indentation" (python3.x only)
You can get some info here.
But basically it's, you are using tabs and spaces in your code.
You don't want that.
Remove all tabs and replaces them by four spaces.
And configure your editor to do that automatically.
Eventually, to come back on your problem:
Just look at the line number of the error, and fix it using the previous information.
I had this same problem and discovered (via this answer to a similar question) that the problem was that I didn't properly indent the docstring properly. Unfortunately IDLE doesn't give useful feedback here, but once I fixed the docstring indentation, the problem went away.
Specifically --- bad code that generates indentation errors:
def my_function(args):
"Here is my docstring"
....
Good code that avoids indentation errors:
def my_function(args):
"Here is my docstring"
....
Note: I'm not saying this is the problem, but that it might be, because in my case, it was!
You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.
in python intended block mean there is every thing must be written in manner in my case I written it this way
def btnClick(numbers):
global operator
operator = operator + str(numbers)
text_input.set(operator)
Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code
def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)
This is just an indentation problem since Python is very strict when it comes to it.
If you are using Sublime, you can select all, click on the lower right beside 'Python' and make sure you check 'Indent using spaces' and choose your Tab Width to be consistent, then Convert Indentation to Spaces to convert all tabs to spaces.