Why is a space counted as a syntax error? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am using Python 3.1 IDLE and have found that the space (which I will mark out as such - _) is being highlighted by IDLE as a syntax error. I would like to know if anyone knows what the problem is and offer a solution. I know it looks wrong, but the underscore is just there to highlight where IDLE says the problem is. I can't work out what the issue with that line and the next line is.
def attrSelection():
while attrChoice!=6
if attrChoice==1:
attrChoice=Power
baseAttr=int(basePow)
attrEditor()
_ elif attrChoice==2:
attrChoice=Health
baseAttr=int(baseHlth)
attrEditor()
elif attrChoice==3
attrChoice=Wisdom
baseAttr=int(baseWis)
attrEditor()
elif attrChoice==4:
attrChoice=Dexterity
baseAttr=int(baseDex)
attrEditor()
elif attrChoice==5:
assignRandom()
else:
print('Option does not exist. Please enter option in range 1-6.')
attrChoice=input('Choice: ')

The IDE may points you to the errors here:
def attrSelection():
while attrChoice!=6
...
elif attrChoice==3
...
You are missing : after the 6 and 3. Otherwise, everything looks fine, assuming you didn't also missed the indentation at the beginning as you are listing the code.

python is really picky about spaces, because it uses spaces for defining code blocks. That's a design choice, it's radical, and has its proponent and opponent. But as a consequence, you need to be really careful in how many spaces you put in front of a line of code, because python will not understand something like:
i = 1
j = 2
k = 3
as logically, it would mean that i, j and k are not in the same blocks, which is impossible as a block shall begin with special statements, usually ending with a colon (:). So python will just throw the same syntax error you've seen in your code saying that there's a problem with spaces!
In your case, it's likely you're using tabs for alignment, which makes two characters to get something aligned at column 8. But somewhere in your code, you had spaces instead of tabs, making it 5 characters to have your code aligned at column 8
<TAB><TAB>i = 1
<TAB> j = 2
so if you consider tabs as spaces, here's what gets written:
i = 1
j = 2
thus python not understanding your code! As a general advice, only use spaces never tabs to indent your code, so you can't be tricked by tab/spaces mess up.
N.B.: as the others are telling, your code is indeed being wrong, missing colons at the end of the following statements:
while attrChoice!=6
...
elif attrChoice==3
...
as they pointed that out, I did not place it in my answer until now. Though if your IDE is giving you an error in the indentation, whereas it's a missing colon, then you should consider changing IDE, as your IDE is really failing at giving relevant errors/warnings that can help code faster and more easily.

There are colons missing after the while and second elif. It scanned fine in idle for me after adding those.

Related

Why do I have "if" expression expected error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm very new to coding and I am learning python alone and this is my code :
from random import *
temp =Randint( 0,70 )
print(temp)
if : temp = 69
print("nice")
You made a few errors
randint is a function so it's first letter should be small case
The for loop syntax was wrong
And we use == for checking equality and = for assignment
You can try the following code below
from random import randint
temp = randint( 0,70 )
print(temp)
if temp == 69:
print("nice")
Your if statement isn't quite right. The colon needs to go at the end of the line, and in an if statement you need a double equals sign (==, which compares two elements) rather than a single equals sign (which assigns a variable). Additionally, you need to indent (put a tab before) lines that are part of a block. You can read more about Python if statements here. The fixed if statement should look like this:
if temp == 69:
print("nice")
Lastly, since Python names are case-sensitive, randint must be in all lowercase.
I hope this is helpful!
A quick thing to remember is that “==“ means two things are equal and “!=“ means if something is not equal.

Why is python giving me an error for improper indentation when my indentation is correct? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
This is the error message I got:
File "main.py", line 15
while True:
^
IndentationError: unindent does not match any outer indentation level
This is my full code:
import wikipedia
from colorama import Fore, Style, Back
y = input("tell me what you want ")
z = int(input("how many sentences "))
try:
text = wikipedia.summary(y, sentences=z)
print('')
print("---Text---")
print(text)
print("----------")
print(len(text.split()),"words.")
except:
print(Fore.RED + "ERROR)
while True:
print("\a")
Can you please explain why this is happening? I am using the Repl online ide.
The answer to this is that I was mixing up tabs and spaces. You shouldn't use both because this error can happen.
While coding in python, it's super important to pay attention to the way you indent. Of course you can either use tab or space, but always make sure you stick with one of them and not mixing them together.
Seems like you haven't done it this time. Delete the indentations and reindent them. Should work fine.

Code works fine when print statement is present, but throws error when I comment the print [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having really strange error. I am using Python 2.7 on Linux Mint OS. Here is the code:
with open(edgeClusteringPath) as f:
for line in f:
clustId = str(currCluster)
spl = line.split(" ")
# print spl
for i in spl:
# print i
(first, second) = edgeNodes[int(float(i))]
nodeClusters.setdefault(first, set())
nodeClusters.setdefault(second, set())
nodeClusters[first].add(clustId)
nodeClusters[second].add(clustId)
# print i
currCluster += 1
edgeClusteringPath is a path to a space separated data and edgeNodes is a dictionary with key = edgeId and value = (firstNode, secondNode). The problem occurs in the second for loop. This code gives me error:
> line 34, in <module>
(first, second) = edgeNodes[int(float(i))]
KeyError: 0
But when I uncomment one (or both) of the print i statements, the execution works fine (without error). It is really strange, I do not see how the print statement could affect the remaining code. I could uncomment the print statement, but I do not actually need that printing, so I would rather get rid of that line.
Here is a sample of edgNodes:
87388: (3250, 6041), 87389: (3250, 6045), 87390: (3250, 6046)
It is a huge dictionary, so I extracted only 3 key-value pairs.
Thank you in advance!
Edit:
Now my code works. I had problem with the paths I have been using. I used wrong file to initialize edgeNodes dictionary and it caused the problems. However, I posted the question just to see if anybody had idea how adding one line changes the behavior of the code. I have been using Java for 3 years and never had similar issue. I am new to Python and do not know how it works internally, so I wished to know if anybody has idea about the effect on one line of the other code.
Thank you for your opinions and suggestions!

I cannot read negative values [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a data set as follows it includes some negative values. I have written codes to read those values. But when any negative numbers percent. It gives error. File format is as below
1SOL HW1 2 1.4788 2.7853 -0.7702
1SOL HW2 3 1.4640 -2.8230 0.6243
2SOL OW 4 -1.5210 0.9510 -2.2050
2SOL HW1 5 1.5960 -0.9780 2.1520
I have written code as follow. I am using for loop and if function to select P[3], P[4], P[5] positions.
X=[]
P = line.split()
x = float(P[3]) `#then I collect these numbers in to array like X = []`
X.append(x)
This code work if there is no negative values.
Then I used following function to write X in to another file. But it is not working
A.write('%s\n' % (X)) `# this is not working since it X is Float. File open as A to write`
Please some one help me to correct my cords.
The reason A.write('%s\n' % (X)) doesn't work has nothing to do with X being a float.
There may be a problem in that (X) isn't a tuple of one float as you seem to expect, it's just a float. Commas make a tuple, not parentheses. In particular, comma-separated values anywhere that they don't have some other meaning (function arguments, list members, etc.) are a tuple. The parentheses are only there to disambiguate a tuple when the comma-separated values would otherwise have another meaning. This is usually simple and intuitive, but it means that in the case of a one-element tuple, you need to write (X,).
However, even that shouldn't be a problem: '%s\n' % 3.2 is '3.2\n'.
On top of that, X isn't actually a float in the first place, it's a list. You explicitly created it as X = [], and then appended each float to it. Again, that's not a problem, but it means you're possibly not getting the output you wanted. This is just a guess, since you never explained what output you wanted or what you were actually getting. But '%s\n' % [3.2, 3.4] is '[3.2, 3.4]\n'. If you wanted each one on a separate line, you have to loop over them, explicitly or implicitly—maybe ''.join('%s\n' % x for x in X).
As for why your negative numbers don't work, there are many possibilities, and it's impossible to guess which without more information, but here are some examples:
There is something that Python (more specifically, split()) considers whitespace, even if it doesn't look like it to you, between the - and the numbers. So, you're trying to convert "-" to a float rather than "-12345".
Those apparent - characters are actually a Unicode minus rather than a hyphen, or something else that looks similar. .decode-ing the file with the right encoding might solve it, but it might not be enough.
There are invisible, non-spacing characters between the - and the first digit. Maybe Unicode again, or maybe just a control character.
In many cases, the exception string (which you didn't show us) will show the repr of the string, which may reveal this information. If not, you can print repr(P[3]) explicitly. If that still doesn't help, try print binascii.hexlify(P[3]) (you'll have to import binascii first, of course).
It's impossible to tell what will work because we can't see your source file, but the problem you're having is with your split function. If I were you, I'd try P = line.split('\t') and see if that resolves your issue.

How can I add a print statement to this code without getting an indentation error [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to python and trying to learn an unfamilar code base. I want to add a print statement just below the def line. But every time I do so for one of these very short methods I get an indentation error.
def rename(self, old, new):
#print 'this will bring an error if left uncommented'
return os.rename(self._full_path(old), self._full_path(new))
How can I add a print statement to a short method like this?
A tab is a tab character (just like \n is a newline character), you can configure most editors to replace a tab character with a certain number of spaces.
The convention in Python is to indent by four spaces and to use spaces instead of tabs. This is the recommendation; but people tend to do what they please.
It is most likely that the code is indented by tabs and you are using spaces. #TimPeters wrote reindent.py that will take a Python file and convert tabs into spaces.
There are other tools as well. Most editors have a function that can do this, if the editor is Python aware they may have a specific function for just this. For example pycharm has a "Convert Indents" menu option under Edit.
Try this code:
def rename(self, old, new):
print('this will bring an error if left uncommented')
return os.rename(self._full_path(old), self._full_path(new))
Whenever I have trouble with the print keyword, I can usually solve it by using print() instead.

Categories