How to use logical operator in Python as compared to PHP in integers?

Viewed 92

I have 2 blocks of code,

test.php -->

$a = 90;
$b = 87;
$c = $a AND $b;
print_r($c);
----------------------
OUTPUT -->
----------------------
90

test.py -->

a = 90
b = 87
c= a and b
print(c)
----------------------
OUTPUT -->
----------------------
87

Now, As I understand both PHP and python when executing the code, interpret the code down to C to machine level (which is the parent language of both)

Then why are they both behaving differently?

What am I doing wrong here?

Thank you for your suggestion.

1 Answers

Code

$a = 90;
$b = 87;
$c = $a AND $b;

is the same as (thanks to operators precedence):

$a = 90;
$b = 87;
($c = $a) AND $b;

So, you just assign $a to $c, and $b... It does nothing.

As for python code:

a = 90
b = 87
c = a and b
print(c)

Python iterpreter returns last value if condition is True. So c is 87. If you write

c = b and a
print(c)

you will see 90. Whoa!

So, if you want same results, the codes should be:

$a = 90;
$b = 87;
$c = $a && $b;
var_dump($c);   // bool(true)

and:

a = 90
b = 87
c = bool(a and b)
print(c)        // True

I assume that you want to check that both variables a and b are truthy.

Related