+ 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

17th Jun 2018, 3:52 PM
李立威
12 Réponses
+ 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)
17th Jun 2018, 4:47 PM
李立威
+ 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
17th Jun 2018, 3:58 PM
‎ ‏‏‎Anonymous Guy
17th Jun 2018, 4:12 PM
‎ ‏‏‎Anonymous Guy
+ 2
that's because a was deleted before line 14
17th Jun 2018, 4:15 PM
‎ ‏‏‎Anonymous Guy
+ 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.
17th Jun 2018, 4:17 PM
Maninder $ingh
Maninder $ingh - avatar
+ 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
17th Jun 2018, 4:05 PM
Maninder $ingh
Maninder $ingh - avatar
+ 1
Sreejith Thanks bro. but this code cause an error at line 14.
17th Jun 2018, 4:14 PM
李立威
+ 1
Sreejith Maninder Singh Thanks you both. I may find another way to do this.
17th Jun 2018, 4:28 PM
李立威
+ 1
李立威 tell me another way.
17th Jun 2018, 4:29 PM
Maninder $ingh
Maninder $ingh - avatar
0
Sreejith Alright. Then how can I del the variable "a" by a function?
17th Jun 2018, 4:00 PM
李立威
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?
17th Jun 2018, 4:10 PM
李立威
- 1
banti
18th Jun 2018, 1:31 AM
Technical jagseer
Technical jagseer - avatar