"if" does not follow a conditional statement

I go through Zed's “Learn Python Hard Way” and I am on ex49. I am rather confused by the following code that it gives:

def peek(word_list): if word_list: # this gives me trouble word = word_list[0] return word[0] else: return None 

The condition of the if gives me problems as commented out. I am not sure if this means that word_list is an object, not a conditional statement. Like word_list , only on its own, should if ?

+5
source share
7 answers

The if applies the built-in bool() function to the next expression. In your case, the code block inside the if run only if bool(word_list) is True .

Various objects in Python evaluate to either True or False in a boolean context. These objects are considered "Truthy" or "Falsy". For instance:

 In [180]: bool('abc') Out[180]: True In [181]: bool('') Out[181]: False In [182]: bool([1, 2, 4]) Out[182]: True In [183]: bool([]) Out[183]: False In [184]: bool(None) Out[184]: False 

The above examples show that:

  • strings of length >= 1 are truthy.
  • empty lines are falsy.
  • length lists >= 1 are truthy.
  • empty lists - Falsy.
  • None - Falsy.

So: if word_list will evaluate to True if this is a non-empty list. However, if it is an empty list or None , it will be evaluated to False .

+7
source

word_list is list , and when you use it for the if condition, you check word_list empty or not:

 word_list = [] bool(word_list) # False if word_list : print "I'm not empty" # would not printed word_list = ['a'] bool(word_list) # True if word_list : print word_list[0] # 'a' 

as a mad physicist said that not even a single element in the list means that it is not empty:

 word_list = [None] bool(word_list) # True 
+6
source

It checks if word_list empty or not. If the list is empty and used in a conditional expression, it evaluates to False. Otherwise, it evaluates to True.

 word_list = ['some value'] if word_list: # list is not empty do some stuff print "I WILL PRINT" word_list = [] if word_list: # list is empty print "I WILL NOT PRINT" 

In the above code, only the first fragment will be printed.

See the following link: https://docs.python.org/2/library/stdtypes.html#truth-value-testing

+6
source

What is required for an if block is simply something that can be evaluated either with True or with False. A conditional is evaluated directly on one of them, but there are other objects that can be converted. To find out what this object is, you can use bool :

 >>> mylist = [] >>> bool(mylist) False >>> mylist = [4, 3, 6] >>> bool(mylist) True 

You see that the list is False if it is empty, but True otherwise. Therefore, the if word_list: block will be evaluated if word_list is word_list empty. Strings are also False if they are empty, but True otherwise. The same with tuples, dictionaries, sets. With numbers 0 and 0.0 False, but any other number is True. A fairly general argument pointing to a function to come up with its own value is None , which evaluates to False, so the if not mylist: block will be executed if mylist empty or if mylist is None . (It will also be executed if mylist is 0 , () , {} , etc., but it is unlikely that it would be given mylist )

+5
source

Take a look at this documentation page for Truth Value Testing in python. After reading, you should get a clear idea of ​​your situation. Here is the relevant part for easy access.

5.1. Verification of the value of truth

Any object can be checked for true, for use in an if or while condition or as an operand of boolean operations below. The following values ​​are considered false:

  • None
  • False
  • zero of any number type, for example 0 , 0.0 , 0j .
  • any empty sequence , for example '' , () , [] .
  • any empty mapping, for example, {} .
  • instances of custom classes if the class defines a __bool__() or __len__() when this method returns the integer 0 or bool is False .

All other values ​​are considered true, so objects of many types are always true.

Read the first sentence again ( bold ) and pay attention to the bold parts in the fourth rule. This is relevant to your question.

So, according to the fourth rule, if your word_list empty, the condition evaluates to False , otherwise it will be True .


I know that you trust the documents, but here is a piece of code that really checks the truth values ​​for itself. (I know that you do not need to do something like this, but I always feel like seeing things with my own eyes)

 def test_truth_value(arg): # ANY object can be evaluated for truth or false in python if arg: # or to be more verbose "if arg is True" print("'{}' is True".format(arg)) else: print("'{}' is False".format(arg)) class dummy_length_zero(): def __len__(self): return 0 def __str__(self): return 'instance of class: "dummy_length_zero"' class dummy_bool_False(): def __bool__(self): return False def __str__(self): return 'instance of class: "dummy_bool_False"' obj_dummy_0 = dummy_length_zero() obj_dummy_false = dummy_bool_False() args = [None, False, 0, 0.0, 0j, '', (), [], {}, obj_dummy_0, obj_dummy_false] for arg in args: test_truth_value(arg) 

And finally, to check this last statement, so objects of many types are always true, just remove the implementation of the __len__() or __bool__() method from the dummy_length_zero or dummy_bool_False respectively, and check the truth.

+3
source

In python, everything has an implicit boolean value. Putting any object in an if directly equivalent (but more Pythonic) than if bool(word_list): None , empty sequences, empty sets, empty dictations, 0 , False , 0.0 are evaluated to False . Most other objects are rated to True . This makes if word_list: most Pythonic way of ensuring that the list is not None or empty before accessing the first item. A long way to express the same thing would be if word_list is not None and len(word_list) > 0:

+2
source

In Python, the expression each can be evaluated to a boolean value (i.e. True or False).

The following basic expressions express False

  • Keyword False (Obviously!)
  • Keyword None
  • Number 0 (0, 0.0 ...)
  • empty sequence (tuple, list, string)
  • empty display (dictionary)

All other expressions evaluate to True.

So what the if statement does is compute the expression that follows the keyword if, either True or False , then act accordingly.

So, in your specific example, if word_list matches any of the above cases, it will be considered False, otherwise it will be considered True.

[#] link

+2
source

Source: https://habr.com/ru/post/1244519/


All Articles