0

I am just exploring the logic of python and the way it works.. I want to know how this code works and what it actually means that made it give these results..

code:

print(str and int)
print(int and str)
print(str or int)
print(int or str)

result:

<class 'int'>
<class 'str'>
<class 'str'>
<class 'int'>
Trachyte
  • 153
  • 1
  • 1
  • 6
  • 3
    Possible duplicate of [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator). Specifically [this answer](https://stackoverflow.com/a/45779600/5858851). – pault Feb 27 '18 at 16:28
  • 2
    `X and Y` is `Y if X else X` whereas `X or Y` is `X if X else Y`. – khelwood Feb 27 '18 at 16:34

4 Answers4

2

From the python doc

 - x or y    -->  if x is false, then y, else x
 - x and y   -->  if x is false, then x, else y
 - not x     -->  if x is false, then True, else False

This means that it returns the item itself not just True or False

Here it mentions:-

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.

So that is why str or int return str and str and int returns int

Praveen
  • 7,752
  • 3
  • 25
  • 44
1

Python uses following approach:

  1. For "and" operator:

    • if left operand is true, then right operand is checked and returned.
    • if left operand is false, then it is returned.
  2. For "or" operator:

    • if left operand is true, then it is returned.
    • if left operand is false, then right operand is returned.

In your case, strand int are classes and so evaluated as true, which fully explains what you observe.

Laurent H.
  • 5,344
  • 1
  • 11
  • 35
0

and gives you the last object on the last condition it checked to check if it's true or false, while or stops at the first one that passes. since both are str and int evaluates to true since they are defined objects, you get them accordingly

To prove and you can do :

print(str and int and bool) #<class bool>

And you are proving or.

MooingRawr
  • 4,446
  • 3
  • 24
  • 29
0

i) Python has "Truthy" and Falsey values, meaning objects are evaluated as True or False in the context of logical operations. For example, the following code prints out "Yay!"

if str:
    print("Yay!")

Same if you replace str with int

ii) and terminates once a False assertion is encountered; or one a True assertion is encountered. Hence and returned the last expression and or returned the first expression in your case since both expressions evaluated to True independently.

haraprasadj
  • 944
  • 1
  • 7
  • 16