Python Operators and Conditional Flow Control

Overview

Python provides several categories of operators for performing computations and comparisons:

  • Arithmetic Operators
  • Comparison Operators
  • Assignment Operators
  • Logical Operators
  • Membership Operators
  • Identity Operators

Additionally, Python supports flow control structures for decision-making in programs.

Arithmetic Operators

a = 21
b = 10
result = 0

result = a + b
print("Addition:", result)  # 31

result = a - b
print("Subtraction:", result)  # 11

result = a * b
print("Multiplication:", result)  # 210

result = a / b
print("Division:", result)  # 2.1

result = a % b
print("Modulus:", result)  # 1

a = 2
b = 3
result = a ** b  # Exponentiation
print("Exponentiation:", result)  # 8

a = 10
b = 5
result = a // b  # Floor division
print("Floor Division:", result)  # 2

Comparison Operators

Comparison operators evaluate relationships between values and return boolean results.

Assignment Operators

Beyond simple assignment with =, Python supports several advanced assignment patterns.

Augmented Assignment

x = 20
y = 3
x %= y
print(x)  # 2

m = 2
n = 3
m **= n
print(m)  # 8

p = 10
q = 3
p //= q
print(p)  # 3

Chained Assignment

Assigning the same value to multiple variables:

x = y = z = 666
print(x, y, z)  # 666 666 666

Unpacking Assignment

items = ['apple', 'banana', 'orange', 'grape']
first, second, third, fourth = items
print(first, second, third, fourth)  # apple banana orange grape

Important: The number of variables must match the number of elements. Mismatched counts raise ValueError.

Using the asterisk for flexible unpacking:

data = ['first', 'middle1', 'middle2', 'middle3', 'last']
first, *middle, last = data
print(middle)  # ['middle1', 'middle2', 'middle3']

name, *remaining = ['kevin', 'jerry', 'tony', 'tank', 'oscar']
print(remaining)  # ['jerry', 'tony', 'tank', 'oscar']

The * operator collects all unmatched values into a list.

Walrus Operator (Python 3.8+)

The walrus operator := assigns a value within an expression, reducing redundant computations.

Standard approach:

a = 15
if a > 10:
    print('Condition met')

Using walrus operator:

if (a := 15) > 10:
    print('Condition met')

In while loops:

Standard approach:

counter = 5
while counter:
    print('Processing...')
    counter -= 1

Walrus operator approach:

counter = 5
while (counter := counter - 1) + 1:
    print('Processing...')

Password validation example:

Standard approach:

while True:
    password = input("Enter password: ")
    if password == "secret":
        break

Walrus operator approach:

while (password := input("Enter password: ")) != "secret":
    continue

Reading file lines:

Standard approach:

file_handle = open("data.txt", "r")
while True:
    line = file_handle.readline()
    if not line:
        break
    print(line.strip())
file_handle.close()

Walrus operator approach:

file_handle = open("data.txt", "r")
while line := file_handle.readline():
    print(line.strip())

In list comprehensions:

Standard approach:

values = [16, 36, 49, 64]
def compute_root(x):
    print('Computing root')
    return x ** 0.5

filtered = [compute_root(i) for i in values if compute_root(i) > 5]

Walrus operator approach:

values = [16, 36, 49, 64]
def compute_root(x):
    print('Computing root')
    return x ** 0.5

filtered = [val for i in values if (val := compute_root(i)) > 5]

Logical Operators

Python uses three logical operators to combine boolean expressions:

  • and: Returns True only when both operands are True
  • or: Returns True when atleast one operand is True
  • not: Inverts the boolean value
x = 10
y = 20

print(x and y)  # 20 (last evaluated value)
print(x or y)   # 10 (first truthy value)
print(not x)    # False

Membership Operators

The in operator checks for membership, while not in checks for absence.

fruits = ['apple', 'mango', 'banana']
print('mango' in fruits)    # True
print('grape' not in fruits)  # True

user_data = {'username': 'admin', 'age': 25}
print('username' in user_data)  # True (keys, not values)
print('admin' in user_data)    # False

With dictionaries, membership tests check for key existence.

Identity Operators

Identity operators compare memory addresses (object identity) rather than values:

  • is: Returns True if both variables reference the same object
  • is not: Returns True if variables reference different objects
list_a = [1, 2, 3, 4]
list_b = [1, 2, 3, 4]

print(list_a == list_b)  # True (same values)
print(list_a is list_b)  # False (different objects)

Key distinction:

  • Equal values do not guarantee equal identity
  • Equal identity guarantees equal values
original = [12, 3]
copy = original
print(copy is original)   # True

slice_copy = original[:]
print(slice_copy is original)  # False
print(slice_copy == original) # True

Flow Control

Execution Flow Types

Programs typically follow three execution patterns:

  1. Sequential: Code executes line by line in order
  2. Branching: Different code paths execute based on conditions
  3. Looping: Code blocks repeat based on conditions

Branching Syntax

age = 18

if age < 26:
    print('Young adult')
else:
    print('Not a young adult')

Rules:

  • Conditions must end with a colon :
  • Indentation (typically 4 spaces) defines code blocks
  • A colon on the previous line indicates the next line requires indentation
  • All conditions evaluate to their boolean equivalent

Single Branch

temperature = 30

if temperature > 25:
    print('It is warm outside')

Dual Branch

age = 20
height = 165
weight = 100
is_student = True

if age < 30 and height >= 160 and weight <= 110 and is_student:
    print('Eligible for discount')
else:
    print('Not eligible')

A dual branch always executes exactly one branch.

Multiple Branches

exam_score = 85

if exam_score >= 90:
    print('Grade: A - Excellent')
elif exam_score >= 80:
    print('Grade: B - Good')
elif exam_score >= 70:
    print('Grade: C - Average')
elif exam_score >= 60:
    print('Grade: D - Passing')
else:
    print('Grade: F - Failed')

Practical Examples

Dog years to human years:

dog_age = int(input("Enter dog's age: "))

if dog_age <= 0:
    print("Invalid input")
elif dog_age == 1:
    print("Equivalent to 14 human years")
elif dog_age == 2:
    print("Equivalent to 22 human years")
elif dog_age > 2:
    human_years = 22 + (dog_age - 2) * 5
    print(f"Equivalent to {human_years} human years")

Number guessing game:

target = 7
guess = -1

print("Number guessing game!")
while guess != target:
    guess = int(input("Enter your guess: "))
    
    if guess == target:
        print("Correct!")
    elif guess < target:
        print("Too low")
    else:
        print("Too high")

Nested conditions:

number = int(input("Enter a number: "))

if number % 2 == 0:
    if number % 3 == 0:
        print("Divisible by both 2 and 3")
    else:
        print("Divisible by 2 only")
else:
    if number % 3 == 0:
        print("Divisible by 3 only")
    else:
        print("Divisible by neither 2 nor 3")

Tags: python Operators flow-control conditional-statements walrus-operator

Posted on Mon, 10 Aug 2026 16:18:10 +0000 by jackie11