Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What does and do
#1
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?
Reply
#2
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
Reply
#3
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
Reply
#4
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)
rsherry8 likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020