Python Forum

Full Version: What does and do
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Please consider the following Python expression where a and b have integer values.

a and b

I claim that value of this expression is 0, if a is 0. If a is non-zero then the value of this expression is b. Do I have this right?

I am also wondering why it would be defined this way. Any idea?
and
True if both the operands are true.

print(0 and 0)
print(0 and 1)
print(1 and 0)
print(1 and 1)
Output:
0 0 0 1
When I execute the following statement:
type( 3 and 4 )
It says the expression is int.

(Apr-28-2021, 11:53 AM)Yoriz Wrote: [ -> ]and
True if both the operands are true.

print(0 and 0)
print(0 and 1)
print(1 and 0)
print(1 and 1)
Output:
0 0 0 1
because
print(3 and 4)
returns an int
Output:
4
This explains it
https://docs.python.org/3/library/stdtyp...and-or-not Wrote:Boolean Operations — and, or, not
These are the Boolean operations, ordered by ascending priority:

Output:
Operation Result Notes x or y if x is false, then y, else x (1) x and y if x is false, then x, else y (2) not x if x is false, then True, else False (3)
Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
  3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

tests = ((0, 0), (0, 1), (1, 0), (1, 1), (3, 4),
         (False, False), (False, True), (True, False), (True, True),
         ('', ''), ('', 'Something'), ('Something', ''), ('Something', 'Something'))

for first, second in tests:
    if result := first and second:
        print(f'(True) ({first}, {second}) result = {result}')
    else:
        print(f'(False) ({first}, {second}) result = {result}')
Output:
(False) (0, 0) result = 0 (False) (0, 1) result = 0 (False) (1, 0) result = 0 (True) (1, 1) result = 1 (True) (3, 4) result = 4 (False) (False, False) result = False (False) (False, True) result = False (False) (True, False) result = False (True) (True, True) result = True (False) (, ) result = (False) (, Something) result = (False) (Something, ) result = (True) (Something, Something) result = Something)