I get a syntax error in the following code:
if value[0] == "ta" or "su":
num_var = len(value)
i = 0
while value[i][0] != "-" and i <= num_var:
if i == 0 and value[0][0].isdigit():
f3["var_%s" %i] = VARFD[[value[0].split("/")[1]]
else:
f3["var_%s" %i] = VARFD[[value[0]]
f4["val_%s" %i] = "T"
i += 1
it claims that the syntax error is on line that starts with "else:". What's wrong with it?
Is your supply of new lines limited or why are you writing code like this?
Your error is here, one ] is missing:
VARFD[[value[0].split("/")[1]]
You're missing a square bracket in the
if i == 0 and value[0][0].isdigit(): f3["var_%s" %i] = VARFD[[value[0].split("/")[1]]
line. But Python code really isn't meant to be this densely written. Space and light!
It's as simple as that you're missing an end bracket on the line before the else.
VARFD[[value[0].split("/")[1]]
I suspect the expression should be
VARFD[value[0].split("/")[1]]
It's pretty much sure sign that you should break apart and simplify your code when errors like this show up :)
Related
This code gives me an indentation error on checks. I get that this happens often, but the instance is in between two for loops that exist because I need to reference two different lists.
I do not even have the data set made yet, but it should report that the syntax is correct at least. The code is fairly simple. I want to automate package placement in a building and I want to do so by taking the biggest packages and putting them in place with the least amount of room where it would still fit.
All inputs that I used so far are dictionaries because I need to know which shelf I am referring too. I am this close to turning it to lists and being extremely strict about formatting.
inv = maxkey["Inventory"]
is the line where the mistake happens. I do not know how to fix it. Should I use lists for this project instead? Is there a flaw in the logic? Is there a parentheses I forgot? Please let me know if this is just an oversight on my part. Please contact me for further details.
def loadOrder(inProd, units, loc, pref, shelves):
items = len(inProd)
while items > 0
# What is the biggest package in the list?
mxw = 0 # Frontal area trackers
BoxId = {} # Identifies what is being selected
for p in inProd:
if p["Height"]*p["Width"] > mxw:
mxw = p["Width"]*p["Height"]
BoxId = p
else:
pass
# What is the location with the least amount of space?
maxi = 0.001
maxkey = {}
for key in loc:
if key["Volume Efficiency"] > maxi and key["Width"] > mxw/BoxId["Height"]:
maxi = key["Volume Efficiency"]
maxkey = key
else:
pass
maxkey["Inventory"].append(BoxId)
weight = 0
volTot = 0
usedL = 0
inv = maxkey["Inventory"]
for k in inv:
weight = k['Weight']+weight
vol = k['Height']*k['Width']*k['Depth']+volTot
usedL = k['Width']+usedL
maxkey["Volume Efficiency"] = volTot/(maxkey['Height']*maxkey['Weight']*maxkey['Depth'])
maxkey['Width Remaining'] = usedL
maxkey['Capacity Remaining'] = weight
del inProd[BoxId]
items = len(inProd)
return [inProd, units, loc, pref, shelves]
Indentation in a function definition should be like:
def function-name():
<some code>
<return something>
Also, you have missed : after while loop condition.
It shoulde be while items > 0:
And you should not mixing the use of tabs and spaces for indentation.
The standard way for indentation is 4 spaces.
you can see more in PEP 8.
I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)
I have a problem in Python language that is described in a title.
for slovo in slova:
if pygame.mouse.get_pressed()[0] and slovo["rect"].collidepoint(pygame.mouse.get_pos()):
for i in range (len(randRijec)):
if slovo["name"] in randRijec[i]:
if i == 0:
slovo1 = randRijec[i].upper()
prvoSlovo = 1
...
...
else:
pogresnoBrojac += 1
slova.remove(slovo)
So, even this IF statement is true, ELSE statement is being executed! However, else statement should be skipped if the if statement is fulfilled.
How to fix this issue?
p.s. I've had this problem few times before and I was not able to solve it...
You have a mixture of tabs and spaces in your code:
Running cat -A test.py (on Unix) yields
for slovo in slova:$
if pygame.mouse.get_pressed()[0] and slovo["rect"].collidepoint(pygame.mouse.get_pos()):$
for i in range (len(randRijec)):$
if slovo["name"] in randRijec[i]:$
if i == 0:$
slovo1 = randRijec[i].upper()$
prvoSlovo = 1$
^I^I^I^I^I^I...$
^I^I^I^I^I^I...$
else:$
pogresnoBrojac += 1$
slova.remove(slovo)$
The ^I indicate tabs.
Thus, the else block is not being interpreted as being at the indentation level on which it appears to be.
Your python code should never mix tabs and spaces for indentation. You can check that your script is not mixing tabs and spaces by running python -t script.py.
In Python you must commit to using either only spaces or only tabs for indentation. PEP8 recommends spaces-only indentation.
You can convert tabs to spaces using the reindent.py program.
So, even this IF statement is true, ELSE statement is being executed!
I can assure you that this is not what happens.
I notice that in the outline of your code the if is inside a for loop. Make sure that in your actual code the else is not accidentally lined up with the for instead of the if. I've seen this mistake more than once.
In Python, for-else is a valid construct. For example, the following is perfectly valid Python:
for i in range(10):
if i < 100:
pass
else:
print 'In else clause'
When run, this prints out In else clause.
Contrast this with the following, which doesn't print anything when run:
for i in range(10):
if i < 100:
pass
else:
print 'In else clause'
It's a question from a long time ago and I stumbled upon it as I was troubleshooting the very same issue - the solution was actually pretty silly and most probably was also the case - as it's a for loop it iterates through every list element, if even one of those elements doesn't fulfill the if condition, it will automatically trigger the else - pretty self-evident but easy to miss for beginners.
Well at least that was the problem in my case :)
Next solution fixed my problem:
for slovo in slova:
if pygame.mouse.get_pressed()[0] and slovo["rect"].collidepoint(pygame.mouse.get_pos()):
xy = 0
for i in range (len(randRijec)):
if slovo["name"] in randRijec[i]:
xy = 1
if i == 0:
slovo1 = randRijec[i].upper()
prvoSlovo = 1
break
if i == 1:
slovo2 = randRijec[i].upper()
drugoSlovo = 1
break
slova.remove(slovo)
if xy == 0:
pogresnoBrojac += 1
...
...
...
xy = 1
pygame.display.update()
time.tick(value)
So, I have just added that xy counter that makes my code work how it should work. When IF statement is met, xy becomes 1, if IF statement isn't fulfilled, xy is set to 0 and then this "else" statement executes. At the end of the code, xy is set to 1 again to prevent executing this "else" (if xy == 0) block.
hi I m wrtng a very simple Python Program to implement Binary Search.
tup=input("enter tup:")
start=0
length=len[tup]
end=tup[length-1]
mid=(int(start)+int(end))/2
key=input("enter value to search")
def search(start,end,key):
if key==tup[mid]
print mid
else if key<tup[mid]
search(start,mid,key)
else if key>tup[mid]
search(mid,end,key)
else
return(-1)
I get an error as
File "binsearch.py", line 8
if key==tup[mid]
^
SyntaxError: invalid syntax
I believe I m missing something trivial but unable to figure out.! Let me know if u feel there are any other errors. thanks :)
if key==tup[mid]
^
needs a : at the end
|
v
if key==tup[mid]:
Same problem in the rest of the statement:
else if key<tup[mid]
^
search(start,mid,key)
else if key>tup[mid]
^
Aside:
Instead of else if consider using Python's neat elif construct, e.g.,
elif key<tup[mid]:
etc.
You need to end all statements that begin a new block with : (i.e. the statements where you increase the indentation level in the next line)
You need to replace else if X with elif X:
You should use raw_input instead of input as the latter evals whatever the user entered.
return is a statement, not a function, so you do not need () around the return value.
When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks
>>> if (n/2) * 2 == n:;
print 'Even';
else: print 'Odd'
SyntaxError: invalid syntax
When I tried to run the above code, I got an invalid syntax error on ELSE
Your indentation is wrong. Try this:
>>> if (n/2) * 2 == n:
... print 'Even'
... else: print 'Odd'
Also you might want to write it on four lines:
>>> if (n/2) * 2 == n:
... print 'Even'
... else:
... print 'Odd'
Or even just one line:
>>> print 'Even' if (n/2) * 2 == n else 'Odd'
One step towards the solution is to remove the semicolon after the if:
if True:; print 'true'; print 'not ok'; # syntax error!
if True: print 'true'; print 'ok'; # ok
You cannot have an else in the same line because it would be ambiguous:
if True: print 't'; if True: print 'tt; else: ... # <- which if is that else for??
It is also clearly stated in the docs that you need a DEDENT before the else statement can start.
Since python 2.5 you can do one line ifs
print ('Even' if n % 2 == 0 else 'Odd')
Still to answer your question you can either:
1. enter the code properly without syntax errors and your blocks will be executed as blocks regardless if they span multiple lines or not, even in interactive shell. See tutorials in dive into python
2. write code in the script and execute that script using either command line or some IDE (idle, eclipse, etc..)
One of the idea behind python is to prefer multiple lines and to aim for uniform formatting of source, so what you try to do is not pythonic, you should not aim to cram multiple statements into single line unless you have a good reason.
print n % 2 == 0 and 'Even' or 'Odd'
:-)