sam
sam

Reputation: 19164

If-statement in Python

I have small doubt in python.

x = ''
if x:
    print 'y'

so, it will never print as 'y'

if I do :

x = 0
if x:
    print 'y'

Then also it will do the same.

Then how can differentiate if I have '' value and 0 value If I have to consider only 0 values?

Upvotes: 0

Views: 283

Answers (5)

Venkat Narayan TL
Venkat Narayan TL

Reputation: 1

This didnt work for u because u didnt add where to enter the number 0 in your program the correct code for this program is :

x = int(input("enter the value of x : "))
if x==0:
    print("Y")

OUTPUT: enter the value of x : 0 Y

Upvotes: 0

moooeeeep
moooeeeep

Reputation: 32502

That is because the object functions __nonzero__() and __len__() will be used to evaluate the condition. From the docs:

object.__nonzero__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __nonzero__(), all its instances are considered true.

By overloading these you can be used to specify such behavior for custom classes as well.

As for if conditions, you can specify exactly what you want to check:

if x: # evaluate boolean value implicitly
  pass
if x is 0: # compare object identity, see also id() function
  pass
if x == 0: # compare the object value
  pass

As for your special case of implicit boolean evaluation: int objects are considered True if they are nonzero; str objects are considered True if their length is nonzero.

Upvotes: 4

Li-aung Yip
Li-aung Yip

Reputation: 12486

I'm not clear on what you actually want - the wording of your question is a little confusing - but this may be illuminating:

>>> test_values = [0,0.00,False,'',None, 1, 1.00, True, 'Foo']
>>> for v in test_values:
    if (not v) and (v != ''):
        print "Got a logically false value, %s, which was not the empty string ''" % v.__repr__()


Got a logically false value, 0, which was not the empty string ''
Got a logically false value, 0.0, which was not the empty string ''
Got a logically false value, False, which was not the empty string ''
Got a logically false value, None, which was not the empty string ''

Upvotes: 0

Abhijit
Abhijit

Reputation: 63707

In python for a condition an empty iterable (here string) evaluated to false.

If you need to check if a value is 0 explicitly you have to say x==0

Upvotes: 3

jamylak
jamylak

Reputation: 133504

if x != '':
    print 'y'

Works only if x is not ''

Upvotes: 2

Related Questions