Get IndexError with exec in Python

254 views Asked by At

I want change sign in if statement. When I use exec

def set_value(array, negation=False):
        equal = "!=" if negation else "=="
        for index1, row in enumerate(pattern_map):
            for index2, column in enumerate(row):   
                exec("if array {} column: kar_map[index1][index2]=1".format(equal))

I get IndexError

Traceback (most recent call last):
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line       234, in <module>
print(kar_map.map_filled)
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line   176, in map_filled
kar_map = self.__class__.filled_map_1(self.__table.count_variable, self.map_pattern, kar_map, variable)
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line 160, in filled_map_1
set_value("")
File "/home/charlie/Desktop/Projects/Python/karnaugh_map.py", line 148, in set_value
exec("if array {} column: kar_map[index1][index2]=1".format(equal))
File "<string>", line 1, in <module>
TypeError: 'Map' object does not support indexing
[Finished in 0.1s with exit code 1]
[cmd: ['/usr/bin/python3.5', '-u', '/home/charlie/Desktop/Projects/Python/karnaugh_map.py']]
[dir: /home/charlie/Desktop/Projects/Python]
[path:    /usr/local/sbin:/usr/local/bin:/usr/bin:/usr/lib/jvm/default/bin:/opt/ope ncascade/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl]

When I don't use exec, it works.

def set_value(array, negation=False):
        for index1, row in enumerate(pattern_map): 
            for index2, column in enumerate(row):   
                if negation:
                    if array != column:
                        kar_map[index1][index2] = 1
                else:
                    if array == column:
                        kar_map[index1][index2] = 1

Anyone have any idea whats the problem?

1

There are 1 answers

0
UnsignedByte On

When using single-line if statements, you put the if part after the code you want to run. In addition, the .format(equal) doesn't make sense. What do you want equal to be? If you want to change the equals sign (=), you should use .format(equals = equal) and change = to {equals}. You should change

exec("if array {} column: kar_map[index1][index2]=1".format(equal))

to

exec("kar_map[index1][index2] {equals} 1 if array {} column".format('=' = equal))