Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "if var" mean in python?

This is a function in python to validate a day entry.

def valid_day(day):
    if day and day.isdigit():#if day
        day = int(day)
        if day > 0 and day <= 31:
            return day

I want to know what the expression if day means (in terms of semantics).

I only know the effect of if on boolean expressions not on variables like integers or arrays.

like image 669
Alcides Avatar asked Dec 27 '13 23:12

Alcides


People also ask

Can we use VAR in Python?

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

What does if not variable mean in Python?

If not statementsNumeric zero (0), empty value or a None object assigned to a variable are all considered False, or True in Python. As x here is True, not x makes it False. Hence, the Else part of the code is executed.

Is var a valid variable name in Python?

The variable name can consist of alphabet letter(s), number(s) and underscore(s) only. For example, myVar , MyVar , _myVar , MyVar123 are valid variable names, but m*var , my-var , 1myVar are invalid variable names. Variable names in Python are case sensitive.


2 Answers

in python, writing

if var:

has the same effect as writing

if bool(var):

(where bool is the built-in bool type which also acts as a constructor function for bool objects).

If the value is already a bool (valued True or False) the meaning is clear -- bool(var) returns the same value. For other types, there's almost always a conversion to bool avaliable which depends on the type. For integers (as in C) it's the same as var!=0; for lists or dicts or strings, it's the same as len(var)!=0, and so forth. You can find this in the python docs.

When you define your own class you can define a method via def __nonzero__(self): , which will be called in this context (when your object is passed to bool explicitly, or implicitly in an if -- or while for that matter).

A notable exception: numpy array objects do not convert to bool (they raise an exception). They need to be explicitly converted using constructs like (arr!=0).any() or (arr>0).all()

On similar lines: Don't get into the habit of writing any of

if x == True:     # This only works as expected when x is a bool, or 0, or 1
if x is True:     # Can be useful but you need to understand what it really means.
if x == None:     # Often works as expected, except when it doesn't

Comparison to None should always be done with

if x is None: (or) if x is not None:

There is only one None object, and x is None will tell you if x refers to that object, and will always give you a bool (True if so, False for any other object). Comparing x==None (a mistake I frequently made when starting to use Python) will usually work, but it activates the generic comparison machinery of Python, which is not what you probably want; if x is an instance of a class, the comparison could raise an exception. is is simple and quick and just does that identity test - it can't be overloaded.

Likewise if x is True means "if x is the boolean object meaning true, and no other object at all" -- which can be useful, but is too narrow for the case when you are just testing truth value. Somebody might end up passing 1, which will fail an 'is True' test, but otherwise acts very much like True.

like image 136
greggo Avatar answered Oct 13 '22 18:10

greggo


Behaviour differs a little bit from language to language.

Behaviour 1: The variable is converted into a boolean. I.e. there are language specific conversions from different types into a boolean. For numeric values, 0 is usually converted into false while any other value is converted to true. As far as I know, this is the way Python does it.

Behaviour 2: Booleans are numeric values. As above, 0 is usually the only value that evaluates to false

Behaviour 3: Any non-null reference evaluates to true, null references evaluate to false.

This should more or less cover it, but there may be other variations or combinations as well, for instance using fallback to method 2 or 3 if 1 is not available. The point is that it's very much a language specific question.

like image 32
Henrik Avatar answered Oct 13 '22 18:10

Henrik