Python AND Operator

Filed Under: Python

Python operators can be divided into multiple categories. Two of them are – bitwise operators and logical operators. Bitwise operator performs operations on integers in binary format whereas logical operators perform operations on boolean values.

Python AND Operator

There are two types of Python AND Operators.

  1. 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.
  2. Logical AND Operator: It’s denoted by and and work with boolean values. The output is boolean – either True or False.

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 Binary Integers

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 < 0 and x > -10:
    print('You entered negative single digit number')
else:
    print('You did not entered single digit integer')

Output:

Python Logical And Operator

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.

You can checkout complete python script and more Python examples from our GitHub Repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages