Using IF, AND, OR with an EQUAL operand together in Python

I am trying to create a function in which a given value (passed as a string) is checked to find out if the number of digits is 4 or 6, and what is the number.

My first impulse was to go with this code:

def number(x):
    if (len(x) == (4 or 6)) and x.isdigit():
        print "True"
    else:
        print "False"

This code above only passes the first test below ... I don’t understand why it passes this, but none of the other tests:

number("1234")

Only when I separate the len () functions will it work correctly.

def number(x):
    if (len(x) == 4 or len(x) == 6) and x.isdigit():
        print "True"
    else:
        print "False"


## Checks
number("1234")
number("123456")
number("abcd")
number("abcdef")
number("1")
number("a")

The above code passes all the tests.

So my questions are:

  • What's going on here?
  • Any way to write cleaner code for this?

Thanks for the help!

** , , , - len(), isdigit() , (- ). .

+4
6

:

if (len(x) == (4 or 6)):

(4 or 6) or. 4 , ==.

, or, , , , true. , .

4 or ... , . Python 4 or. (, 0), or.

, print 4 or 6. 4.

, 4 , if (len(x) == 4) - , 4 , 6 .

, , len(x) 4 6. :

if(len(x) == 4 or len(x) == 6 ...

if(len(x) in (4,6) ...
+2

in :

def number(x):
    if len(x) in (4, 6) and x.isdigit():
    print "True"
else:
    print "False"

in . , 4 or 6 - , . python:

>>> 4 or 6
4
+5

: len(x) in [4, 6] len(x) == 4 or len(x) == 6.

"" . (4 6) () . 4, .

+2

,

if (len(x) in (4, 6)) and x.isdigit():

if (len(x) == (4 or 6)) and x.isdigit(): 
+1

?

. , .

def number(x): 
    return len(x) in {4, 6} and x.isdigit()

print(number("1234")) # True

Then just use your method in the if-statement without string comparison.

+1
source

The problem is in your expression or.

Any value greater than one will be evaluated before Truewhen you put it in the conditional. This way (4 or 6)it will always allow true.

You can use the operator inabove, or you can just use two ==:

if (len(x) == 4 or len(x) == 6) and x.isdigit()

It's a little bit more verbose, it’s easier for me to read.

0
source

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


All Articles