+ 1
why when I try to make my_id += 1 gives me an error
here is my code : my_dict = { 'x': 0, 'y': 0 } temp = {} my_id = 0 def new(my): for i in range(5): my['x'] = int(input(f'x{i} : ')) my['y'] = int(input(f'y{i} : ')) temp[f'{my_id}'] = my print(temp) #my_id += 1 new(my_dict) why when I try to make my_id += 1 gives me an error
5 Respuestas
+ 3
Alisa Zaiceva In Python, you can read a global variable with no problem, but when you write to it Python makes a local variable instead, this avoids the risk of accidentally modifying a global variable. As JaScript mentioned, you can use the global keyword to declare global instead of local.
+ 4
Alisa Zaiceva ,
may be a bit late, but have a look at it. you can pass the my_id var as a second argument to the function and use it there. you should not work with global variables, as long as there is an other option:
my_dict = {
'x': 0,
'y': 0
}
temp = {}
my_id = 0
def new(my, my_id):
for i in range(5):
my['x'] = int(input(f'x{i} : '))
my['y'] = int(input(f'y{i} : '))
temp[f'{my_id}'] = my
print(temp)
my_id += 1
new(my_dict, my_id)
# if you need to get the last value from my_id in the main scope, you can return the value from the function
+ 2
The variable should be deckared global as here:
def new(my):
global my_id
for i in range(5):
my['x'] = int(input(f'x{i} : '))
my['y'] = int(input(f'y{i} : '))
temp[f'{my_id}'] = my
print(temp)
my_id += 1
my_id = 0
my_dict = {
'x': 0,
'y': 0
}
temp = {}
new(my_dict)
+ 1
but they are also defined above the function. Shouldn't they be global?
0
Thank you very much