Python if statement AND operator | Example code

You can combine multiple conditions into a single expression in Python if onditional statements using the “and” operator. It could avoid writing nested if statements.

Example If Statement with AND Operator in Python

Simple python example code. Use AND logical operator in If statement to join two boolean conditions to form a compound expression.

if a==1 and b>0:

Advantage of and operator

a = 1
b = 2

# nested if
if a == 1:
    if b > 0:
        print('a is 1 and', b, 'is greater than zero.')

# Using AND
if a == 1 and b > 0:
    print('a is 1 and', b, 'is greater than zero.')

Output:

Python if statement AND operator

Summarized the operator “equivalents” in this table:

Operator (other languages)Operator (Python)
&&and
||or
!not

Do comment if you have any doubts and suggestions on this Python if statement topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.