-1

In JAVA the below code gives output as "hi"

boolean b=True;
if (b=False) 
{ 
    SOP("hello"); 
} 
else 
{ 
    SOP("hi"); 
}

The same login in Python-2.7 does not work. Why???????

b=True
if (b=False):
        print "hello"
else:
        print "hi"
Jay Joshi
  • 868
  • 8
  • 24
Anith
  • 7
  • 1

2 Answers2

1

A single equal sign, that is, =, is used for variable assignment.

For comparison, you must use double equals ==. So replace your if line with this:

if (b==False):

In addition to this, the parentheses in Python are unnecessary. You could write:

if b == False:

And it would still work. Since b is a boolean value (True or False), you can also do

if not b:

  • But when it "=" works for JAVA where "==" is a comparison operator in JAVA Dont the same apply for python???... – Anith Nov 24 '17 at 10:39
  • @Anith I'm not very familiar with Java, but my guess is that assignment is a function that returns 0. Since 0 cast to a boolean is false, that's why your code works. It's not really expected behaviour, though. Try changin the condition to `if (b=true)` and see if it outputs the same thing. My guess is that it will. – Pedro von Hertwig Batista Nov 24 '17 at 10:48
  • @Anith for Java https://stackoverflow.com/questions/2393988/getting-confused-with-and-in-if-statement .. `if(b=false)` evaluates to `if(b)` which is false – Suraj Rao Nov 24 '17 at 11:01
  • @PedrovonHertwig not really.. check my comment above – Suraj Rao Nov 24 '17 at 11:05
1

b is already a boolean, there's no need to compare it to another boolean.

b = True
if not b:
    print("hello")
else:
    print("hi")

or simply reverse the logic:

b = True
if b:
    print("hi")
else:
    print("hello")

And if you did compare it to False, you'd write b == False, not b = False.

Finally, in Python, an assignment is a statement, not an expression. This was a deliberate choice, in order to avoid bugs when writing if (b = x) instead of if (b == x).

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
  • But when it "=" works for JAVA where "==" is a comparison operator in JAVA Dont the same apply for python???... – Anith Nov 24 '17 at 10:39