+ 1
Why this code doesn't work? Is it possible to define a function that can "del" something in Python?
I wrote this code, expecting that either the function "delete" or "delete2" can del the global variable "a", but it doesn't work. Is it possible to define a function that can "del" something in Python? https://code.sololearn.com/cc5V208kH0s3/?ref=app
12 odpowiedzi
+ 2
Thanks, Sreejith and Maninder Singh.
I finally made it.
I answered to my own question:
the function "delete6" seems to work. Check it out.
a=1
def delete6(x):
for i in globals():
if id(x)==id(globals()[i]):
globals().pop(i)
break
delete6(a) #it works
print(6,a)
or briefly:
a=1
def delete6(x):
d=globals()
for i in d:
if id(x)==id(d[i]):
d.pop(i)
break
delete6(a) #it works
print(6,a)
+ 2
you cannot convert parameter of any function to global
remove line no. 10
read this for more info.
https://stackoverflow.com/questions/18807749/name-x-is-parameter-and-global-JUMP_LINK__&&__python__&&__JUMP_LINK
+ 2
李立威 return value of x
https://code.sololearn.com/c5679y5cKYjQ/?ref=app
+ 2
that's because a was deleted before line 14
+ 2
李立威 right because global only work with real name variables.and if you pass parameter in function and don't use global and use del statement ,it only delete parameter of function not real variable.
+ 1
here is right code man.
if you want to use global then you need to write real name of variable.
https://code.sololearn.com/cn9tHBvx1dqf/?ref=app
+ 1
Sreejith
Thanks bro. but this code cause an error at line 14.
+ 1
Sreejith Maninder Singh
Thanks you both. I may find another way to do this.
+ 1
李立威 tell me another way.
0
Sreejith
Alright. Then how can I del the variable "a" by a function?
0
Maninder Singh
Thanks. So it is not possible to define a function with a parameter x, which can del the variable with name "x", right?
- 1
banti