04 Lecture operators in python 2023-2
04 Lecture operators in python 2023-2
== Equal to x==10
!= Not Equal to x!=5
> Greater than x>5
< Less than x<5
>= Greater or Equal to x>=5
<= Less than or equal to x<=5
Operators in Python
Python Logical operators
Logical operators are used to combine conditional statements:
and age>18 and age<60 //returns True if both conditions are true.
or age>18 or age<60
not not(age>18 and age<60)
Boolean Expressions in Python
A boolean expression is an expression that is either true or false.
>>> 5 == 5
In the above example, == is used which compares the value of given
two operands and returns true if they are equal, else False.
Operators in Python
In Python, True and False are equivalent to 1 and 0, respectively.
>>> 0 == False
>>> 1 == True
>>> 2 == True
>>> bool(0) // it will cast the integer to its equivalent Boolean value: False
>>> bool(1) // it will cast the integer to its equivalent Boolean value: True
>>> bool(2) // it will cast the integer to its Boolean value: True
>>>bool(-2) // it will cast the integer to its Boolean value: True
While casting to Boolean, All other values, including non-zero numbers, non-empty
strings (like "hello"), non-empty lists, and other non-empty collections, are considered
True.
Operators in Python
>>> True + (False / True) // Output?
Operators in Python
>>> True + (False / True) // Output?
Since, arithmetic operator is used, so each bool value is converted implicitly to their Integer
equivalent before performing the operation.
In the above example, True + (False / True) can be expressed as 1 + (0/1) whose output is 1.0
Operators in Python
>>> 17 and True // Output?
the operands of the logical operators should be boolean expressions, but Python is not very strict. Any
nonzero number is interpreted as “true.”
Bitwise NOT (~): Inverts all the bits (flips 0 to 1 and 1 to 0).
~5 returns output 2
Bitwise XOR (^): Sets each bit to 1 if only one of the bits is 1.