Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

python 0 assigner returns none despite the value

I have a problem in python(python 3.9 on VS Code). I'm trying to change a value in a dictionary by some conditions:

def getset(age):
    age['age']+=0 if age['age']>=0 else age['age'] == 0
mammad = {'name': 'mammad', 'age': -3}
mammad = getset(mammad)
print(mammad)

as you can see in age['age']+=0 if age['age']>=0 else age['age'] == 0 age key has to have a value of 0 if it's lower than 0. But anyway, it changes it to none. What's the problem?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to return the dict after you make changes to it (you are assigning None from the function call when it returns nothing) or just call the function without assigning it to your variable since it will modify the dict in-place anyway. You can change the dictionary like this:

def getset(age):
    age['age'] = 0 if age['age'] < 0 else age['age']

mammad = {'name': 'mammad', 'age': -3}
# no need to 'assign' to 'mammad' again, you changed it already!
getset(mammad)
>>> print(mammad)
{'name': 'mammad', 'age': 0}

A function which returns nothing prints nothing (None).

>>> def f():
...     pass
... 
>>> print(f())
None

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...