I tried to write code as below:
for i in range(1,13):
'test{}'.format(i) = """
select * from test_table where month(date_time) = {}
""".format(i)
But I got the following syntax error: SyntaxError: can't assign to function call
.
How can I fix this?
CodePudding user response:
You can use a dictionary instead:
d = {}
for i in range(1, 13):
d["test{0}".format(i)] = "select * from test_table where month(date_time) = {0}".format(i)
print(d)
Output:
{'test1': 'select * from test_table where month(date_time) = 1', 'test2': 'select * from test_table where month(date_time) = 2', 'test3': 'select * from test_table where month(date_time) = 3', 'test4': 'select * from test_table where month(date_time) = 4', 'test5': 'select * from test_table where month(date_time) = 5', 'test6': 'select * from test_table where month(date_time) = 6', 'test7': 'select * from test_table where month(date_time) = 7', 'test8': 'select * from test_table where month(date_time) = 8', 'test9': 'select * from test_table where month(date_time) = 9', 'test10': 'select * from test_table where month(date_time) = 10', 'test11': 'select * from test_table where month(date_time) = 11', 'test12': 'select * from test_table where month(date_time) = 12'}
Now you can access a certain key like:
print(d['test3'])
to get a certain value:
select * from test_table where month(date_time) = 3
You could also do something like:
for i in range(1, 13):
globals()['test%s' % i] = "select * from test_table where month(date_time) = {0}".format(i)
print(test3)
to get
select * from test_table where month(date_time) = 3
but this is a bad practice, usually dictionaries or lists should be used in these scenarios.
CodePudding user response:
In this particular problem you are using 1 = symbol which shows that you are trying to assign a value. First try fixing the symbol and then check