Python AND Operator
There are two types of Python AND Operators.
- Bitwise AND Operator: It’s denoted by
&
and work with integers. The numbers are converted into binary format and bitwise AND operation is performed. Finally, the output is returned in the decimal format. - Logical AND Operator: It’s denoted by
and
and work with boolean values. The output is boolean – eitherTrue
orFalse
.
Python Bitwise AND Operator Example
Let’s look at an example of bitwise and operator. We will ask the user to enter two numbers and print their binary and operation output.
a = int(input('Please enter an integer:n'))
b = int(input('Please enter another integer:n'))
print(f'{a} in binary is {str(bin(a))[2:]}')
print(f'{b} in binary is {str(bin(b))[2:]}')
print(f'Binary AND of {a} and {b} is {a&b}')
Output:
Python And Operator – Bitwise
Python Logical AND Operator Example
Let’s look at an example of logical and operator. We will ask the user to enter a single digit number and print if it’s positive or negative. If the user doesn’t enter single digit integer, then we will print it too.
x = int(input('Please enter a single digit integer:n'))
if x > 0 and x < 10:
print('You entered positive single digit number')
elif x -10:
print('You entered negative single digit number')
else:
print('You did not entered single digit integer')
Output:
Python Logical And Operator
Summary
Python provides a lot of operators to work with different kinds of data types. Here we learned how to use Python and operators with boolean and bitwise binary integers.