Tuesday, February 13, 2018

Is it possible only to declare a variable without assigning any value in Python?



Is it possible to declare a variable in Python, like so?:




var


so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?



EDIT: I want to do this for cases like this:



value


for index in sequence:

if value == None and conditionMet:
value = index
break


Duplicate






Related




Answer



Why not just do this:



var = None



Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.



This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful if you can.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...