0% found this document useful (0 votes)
3 views32 pages

Python Conditions DeepDive

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views32 pages

Python Conditions DeepDive

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Python Deep Dive


Conditions — if, elif & else

Complete Guide — Every Operator, Pattern & DevNet Example


Comparison • Logical • Membership • Identity • Ternary • match/case

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 1 — What Are Conditions?

A condition is an expression that evaluates to either True or False. Conditions allow your code
to make decisions — run different blocks of code depending on the situation.

Real-World Analogy
Think of a traffic light. If the light is green → drive. Elif it is amber → slow down. Else → stop.
In network automation: If the API returns 200 → process the data.
Elif it returns 401 → re-authenticate.
Else → log the error and skip.

1.1 Why Conditions Matter in DevNet


• React to API responses — Different HTTP status codes need different handling.
• Validate data — Check if a field exists, has the right type, or is in a valid range.
• Control automation flow — Only configure devices that are reachable and active.
• Error handling — Check for missing data before processing it.
• Business logic — Apply different configs to routers vs switches vs firewalls.

1.2 How Python Evaluates Conditions


Python evaluates any condition expression to a boolean — True or False. The if/elif/else
keywords then decide which block of code runs.

# Python evaluates the expression after 'if'


# If it is True → run the indented block
# If it is False → skip it

x = 10
if x > 5: # 10 > 5 is True → block runs
print("x is big") # ← this prints

if x > 20: # 10 > 20 is False → block skipped


print("x is huge") # ← this never runs

# The evaluated value does NOT have to be literally True/False


# Python uses "truthiness" — any value evaluates to True or False
if 1: # 1 is truthy → runs
print("1 is truthy")

if "hello": # non-empty string → truthy → runs


print("string is truthy")

if []: # empty list → falsy → skipped


print("this never runs")

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 2 — The if Statement

The if statement is the most basic decision-making tool. It runs a block of code ONLY when a
condition is True. If the condition is False, the block is completely skipped.

2.1 Basic Syntax


# Syntax:
#
# if condition:
# code block ← must be indented (4 spaces)
#
# The colon (:) at the end of the if line is REQUIRED
# The indented block is called the "body" of the if statement

status_code = 200

if status_code == 200:
print("Request was successful!")
print("Processing the data now...")

# ↑ Both lines are in the if block (same indentation level)


# They both run when status_code == 200

# After the if block, code continues normally regardless


print("This always runs, inside or outside the if block")

Critical Rule — Indentation


Python uses INDENTATION to define code blocks — not curly braces like other languages.
The standard is 4 spaces per level. Never mix tabs and spaces.
Every line in the if block MUST be indented by the same amount.
If the indentation is wrong, Python raises an IndentationError.

2.2 if Statement — Multiple Lines in the Block


device = {"hostname": "R1", "ip": "[Link]", "active": True}

if device["active"]:
# All these lines are inside the if block
print(f"Processing device: {device['hostname']}")
ip = device["ip"]
print(f"Connecting to {ip}...")
print("Configuration applied successfully")

# This line is OUTSIDE the if block (no indentation)


print("Done processing all devices")

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

2.3 Simple if — Real DevNet Examples


import requests

# ── Example 1: Check API response status ─────────────────────


response = [Link]("[Link] headers={}, verify=False)

if response.status_code == 200:
devices = [Link]()["response"]
print(f"Got {len(devices)} devices")

# ── Example 2: Check if a device is reachable ─────────────────


device = {"hostname": "R1", "reachabilityStatus": "Reachable"}

if [Link]("reachabilityStatus") == "Reachable":
print(f"{device['hostname']} is online — proceeding with config")

# ── Example 3: Check if a list is not empty ───────────────────


unreachable_devices = ["SW1", "SW3"]

if unreachable_devices: # Truthy check — True if list has items


print(f"WARNING: {len(unreachable_devices)} devices unreachable!")

# ── Example 4: Check if a key exists before using it ─────────


api_data = {"hostname": "R1", "ip": "[Link]"}

if "ip" in api_data:
print(f"IP Address: {api_data['ip']}")

# ── Example 5: Validate a port number before connecting ───────


port = 8080

if 1 <= port <= 65535:


print(f"Valid port: {port}")
# proceed with connection

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 3 — The if / else Statement

The else clause adds a fallback block that runs when the if condition is False. It gives you two
paths: one for True, one for False.

3.1 Basic if / else Syntax


# Syntax:
#
# if condition:
# runs when condition is TRUE
# else:
# runs when condition is FALSE
#
# Only ONE of the two blocks ever runs — never both!

status_code = 404

if status_code == 200:
print("Success! Data received.")
else:
print("Something went wrong!")

# ────────────────────────────────────────────────────────────
# More detailed example
device = {"hostname": "R1", "active": False}

if device["active"]:
print(f"{device['hostname']} is UP — configuring...")
else:
print(f"{device['hostname']} is DOWN — skipping")

3.2 else — Real DevNet Examples


# ── Example 1: Handle API success vs failure ─────────────────
response = [Link](url, headers=headers, verify=False)

if response.status_code == 200:
data = [Link]()
print(f"Success! Got {len(data['response'])} devices")
else:
print(f"API Error: {response.status_code}")
print(f"Message: {[Link]}")

# ── Example 2: Device reachability check ─────────────────────


def process_device(device):
if [Link]("reachabilityStatus") == "Reachable":
print(f" Configuring {device['hostname']}...")
apply_config(device)
else:

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

print(f" Skipping {device['hostname']} — unreachable")

# ── Example 3: Token validation ───────────────────────────────


token = get_auth_token()

if token: # Truthy — True if token is a non-empty string


make_api_calls(token)
else:
print("Authentication failed! Cannot proceed.")

# ── Example 4: File existence check ──────────────────────────


import os
config_file = "device_list.json"

if [Link](config_file):
with open(config_file) as f:
devices = [Link](f)
else:
print(f"Config file not found: {config_file}")
devices = []

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 4 — The if / elif / else Statement

elif (short for 'else if') lets you check multiple conditions one after another. Python checks each
condition in order and runs only the FIRST block that is True. The else at the end is the fallback
if nothing matched.

4.1 Basic if / elif / else Syntax


# Syntax:
#
# if condition_1:
# runs if condition_1 is True
# elif condition_2:
# runs if condition_1 is False AND condition_2 is True
# elif condition_3:
# runs if condition_1 AND 2 are False AND condition_3 is True
# else:
# runs if ALL conditions above are False
#
# KEY RULE: Only the FIRST matching block runs — the rest are skipped!

status_code = 401

if status_code == 200:
print("200 OK — Success")
elif status_code == 201:
print("201 Created — New resource made")
elif status_code == 401:
print("401 Unauthorized — check your token") # ← this runs
elif status_code == 403:
print("403 Forbidden — no permission")
elif status_code == 404:
print("404 Not Found — check the URL")
else:
print(f"Unexpected status: {status_code}")

4.2 How Python Evaluates elif — Step by Step


cpu = 75

# Python checks each condition TOP TO BOTTOM


# It STOPS at the first True condition

if cpu >= 90: # Step 1: Is 75 >= 90? → No (False) → skip


print("CRITICAL")
elif cpu >= 75: # Step 2: Is 75 >= 75? → Yes (True) → RUN!
print("WARNING") # ← This runs
elif cpu >= 50: # Step 3: NOT checked — already found a match
print("MODERATE")
else: # Step 4: NOT checked — already found a match

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

print("OK")

# IMPORTANT: Order matters!


# Putting >= 50 before >= 75 would give wrong results:
if cpu >= 50: # 75 >= 50 is True — would match here FIRST
print("MODERATE") # Wrong! Would always match >= 50 before >= 75
elif cpu >= 75:
print("WARNING") # Never reached!

Order Matters in elif!


Python checks conditions from TOP to BOTTOM and stops at the FIRST match.
Always put the MOST SPECIFIC (narrowest) conditions FIRST.
Put BROADER conditions later — otherwise they will catch everything before specific ones.
Example: Check >= 90 before >= 75 before >= 50.

4.3 elif — Real DevNet Examples


# ── Example 1: Full HTTP status code handler ─────────────────
def handle_response(response):
code = response.status_code

if code == 200:
return [Link]()
elif code == 201:
print("Resource created successfully")
return [Link]()
elif code == 204:
print("Success — no content returned")
return {}
elif code == 400:
print(f"Bad Request — check your data: {[Link]}")
return None
elif code == 401:
print("Unauthorized — token expired, re-authenticating...")
return None
elif code == 403:
print("Forbidden — insufficient permissions")
return None
elif code == 404:
print(f"Not Found — check the URL: {[Link]}")
return None
elif code == 429:
print("Rate limit hit — waiting before retrying...")
return None
elif 500 <= code <= 599:
print(f"Server Error {code} — try again later")
return None
else:
print(f"Unexpected status code: {code}")
return None

# ── Example 2: Device family routing ─────────────────────────


def configure_device(device):
family = [Link]("family", "Unknown")

if family == "Routers":

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

apply_router_config(device)
print(f"Router config applied to {device['hostname']}")
elif family == "Switches":
apply_switch_config(device)
print(f"Switch config applied to {device['hostname']}")
elif family == "Wireless":
apply_wireless_config(device)
print(f"Wireless config applied to {device['hostname']}")
elif family == "Security":
print(f"Firewall {device['hostname']} — manual config required")
else:
print(f"Unknown family '{family}' — skipping {device['hostname']}")

# ── Example 3: CPU alert levels ──────────────────────────────


def cpu_alert(hostname, cpu_percent):
if cpu_percent >= 95:
send_alert("CRITICAL", hostname, cpu_percent)
page_on_call_engineer(hostname)
elif cpu_percent >= 80:
send_alert("HIGH", hostname, cpu_percent)
log_warning(hostname, cpu_percent)
elif cpu_percent >= 60:
log_warning(hostname, cpu_percent)
print(f"Elevated CPU on {hostname}: {cpu_percent}%")
else:
print(f"CPU normal on {hostname}: {cpu_percent}%")

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 5 — Comparison Operators

Comparison operators compare two values and return True or False. They are the building
blocks of every condition.

5.1 All Comparison Operators


Operato Name Example Result Notes
r
== Equal to 5 == 5 True Value equality — NOT
assignment
!= Not equal to 5 != 3 True True when values differ
> Greater than 10 > 5 True Strict — equal does not
match
< Less than 3 < 10 True Strict — equal does not
match
>= Greater than or equal 5 >= 5 True Matches equal AND
greater
<= Less than or equal 3 <= 5 True Matches equal AND
smaller
in Member of "r1" in lst True Works on lists, dicts,
strings
not in Not a member "r9" not in lst True Opposite of in
is Same object in x is None True Identity check — use for
memory None
is not Different object x is not None True Use instead of != for
None

5.2 == vs is — Critical Difference


# == checks if VALUES are equal
# is checks if they are the EXACT SAME OBJECT in memory

# Comparing values
print(1 == 1) # True — same value
print(1 == 1.0) # True — same value (int vs float)
print("R1" == "R1") # True — same value

# Comparing identity
a = [1, 2, 3]

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

b = [1, 2, 3]
c = a # c points to the SAME object as a

print(a == b) # True — same values


print(a is b) # False — different objects in memory
print(a is c) # True — same object!

# ── ALWAYS use 'is' for None comparisons ──────────────────────


token = None

# Wrong way:
if token == None: # Works, but not Pythonic
print("No token")

# Correct way:
if token is None: # Always use 'is' for None
print("No token")

if token is not None: # Check that something is NOT None


print(f"Token: {token}")

5.3 Chained Comparisons — Python Unique Feature


# Python allows chaining comparisons — very readable!
# These work differently from other languages

port = 8080

# Old way (other languages):


if port >= 1024 and port <= 65535:
print("Valid non-privileged port")

# Python way — chained comparison (cleaner!):


if 1024 <= port <= 65535:
print("Valid non-privileged port")

# More examples
cpu = 75
if 60 <= cpu < 80: # 60 ≤ cpu AND cpu < 80
print("CPU moderate")

vlan_id = 100
if 1 <= vlan_id <= 4094:
print(f"Valid VLAN ID: {vlan_id}")

# Negative example:
# if 0 < vlan_id < 4095: # Same thing, also valid

5.4 Comparing Strings


# String comparison is case-sensitive and alphabetical
print("apple" == "apple") # True
print("Apple" == "apple") # False (capital A vs lowercase a)
print("apple" < "banana") # True (alphabetical)
print("z" > "a") # True

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

# ── Always normalise case before comparing ────────────────────


family = "routers" # could be any case from API

if [Link]() == "routers": # .lower() makes it safe


print("This is a router")

# ── Check if a string contains a substring ────────────────────


hostname = "Core-Router-HQ"

if "Router" in hostname:
print("This is a router")

if [Link]("Core"):
print("This is a core device")

if [Link]("HQ"):
print("This device is at HQ")

# ── Common mistake: = instead of == ──────────────────────────


# if family = "Routers": ← SyntaxError! = is assignment, not comparison
# if family == "Routers": ← Correct!

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 6 — Logical Operators (and, or, not)

Logical operators combine multiple conditions into one. They are essential when you need to
check two or more things at the same time.

6.1 and — Both Must Be True


# and returns True only when BOTH sides are True
# If the LEFT side is False, Python does NOT check the right side (short-circuit)

cpu = 85
memory = 72

if cpu > 80 and memory > 60:


print("Both CPU and memory are high — sending alert!")

# Truth table for 'and'


print(True and True) # True
print(True and False) # False
print(False and True) # False
print(False and False) # False

# Real DevNet examples


device = {"hostname": "R1", "active": True, "cpu": 90}

# Must be both active AND high CPU


if device["active"] and device["cpu"] > 80:
send_cpu_alert(device["hostname"])

# Multiple conditions chained


if status == 200 and data is not None and len(data) > 0:
process(data)

# ── Short-circuit evaluation ──────────────────────────────────


# If the first condition is False, Python SKIPS the second
# This prevents errors when the second check would crash on None

response = None
# SAFE: Python won't try [Link]() because response is None
if response is not None and response.status_code == 200:
data = [Link]()

6.2 or — At Least One Must Be True


# or returns True when AT LEAST ONE side is True
# If the LEFT side is True, Python does NOT check the right side (short-circuit)

cpu = 95
memory = 45

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

if cpu > 90 or memory > 90:


print("At least one metric is critical!")

# Truth table for 'or'


print(True or True) # True
print(True or False) # True
print(False or True) # True
print(False or False) # False

# Real DevNet examples


device = {"hostname": "R1", "family": "Routers"}

# Either a router OR a firewall gets this config


if device["family"] == "Routers" or device["family"] == "Security":
apply_routing_policy(device)

# Even better with 'in':


if device["family"] in ["Routers", "Security"]:
apply_routing_policy(device)

# ── or as a default value trick ───────────────────────────────


# If the first value is falsy, use the second
hostname = [Link]("hostname") or "unknown"
location = [Link]("location") or "Not set"
print(hostname, location)

6.3 not — Invert a Condition


# not inverts True → False and False → True

is_down = False

if not is_down:
print("Device is UP!") # ← runs because not False = True

# Equivalent to:
if is_down == False: # Less Pythonic
print("Device is UP!")

# Real DevNet examples


device = {"active": True}

if not device["active"]:
print("Device offline — skipping")

# Not with membership check


blocked_vendors = ["Huawei", "ZTE"]
vendor = "Cisco"

if vendor not in blocked_vendors: # Cleaner than: not (vendor in


blocked_vendors)
print(f"{vendor} is an approved vendor")

# Not with None check


token = None
if not token: # True when token is None, empty string, 0, etc.
token = authenticate() # Get a new token

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

6.4 Combining Logical Operators — Precedence


# Precedence order (highest to lowest):
# 1. not
# 2. and
# 3. or
#
# This means: not is evaluated first, then and, then or
# Use parentheses () to make the order explicit and clear!

cpu = 85
memory = 90
disk = 40

# Without parentheses — can be confusing


if cpu > 80 and memory > 80 or disk > 90:
# Python reads this as: (cpu > 80 and memory > 80) or (disk > 90)
print("Alert!")

# With parentheses — crystal clear intent


if (cpu > 80 and memory > 80) or disk > 90:
print("Alert: both compute resources high, OR disk is critical")

# Different meaning with different parentheses:


if cpu > 80 and (memory > 80 or disk > 90):
print("Alert: CPU high AND (memory high OR disk high)")

# Real DevNet best practice


device = {"active": True, "family": "Routers", "cpu": 90}

# Clear, readable with parentheses


if (device["active"] and
device["family"] == "Routers" and
device["cpu"] > 85):
send_router_cpu_alert(device)

6.5 Logical Operators Truth Table — Full Reference


A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 7 — Truthy & Falsy Values

Python's if statement does not require a literal True or False — it accepts any value and decides
whether it is 'truthy' (acts like True) or 'falsy' (acts like False). This is one of Python's most
powerful features.

7.1 Falsy Values — Everything That Acts Like False


# These ALL evaluate to False in an if condition:

if 0: print("runs") # ← does NOT run (0 is falsy)


if 0.0: print("runs") # ← does NOT run
if "": print("runs") # ← does NOT run (empty string)
if []: print("runs") # ← does NOT run (empty list)
if {}: print("runs") # ← does NOT run (empty dict)
if (): print("runs") # ← does NOT run (empty tuple)
if set(): print("runs") # ← does NOT run (empty set)
if None: print("runs") # ← does NOT run
if False: print("runs") # ← does NOT run

# ── Truthy: everything else ───────────────────────────────────


if 1: print("runs") # ← RUNS (non-zero number)
if -5: print("runs") # ← RUNS (any non-zero, even negative)
if "hello": print("runs") # ← RUNS (non-empty string)
if [0]: print("runs") # ← RUNS (list with items, even [False]!)
if {"k": "v"}: print("runs") # ← RUNS (non-empty dict)
if True: print("runs") # ← RUNS

7.2 Using Truthiness in DevNet Code


# ── Check if a list has items ────────────────────────────────
devices = get_unreachable_devices()

if devices: # True if list is not empty


print(f"{len(devices)} unreachable!")
else:
print("All devices are reachable!")

# ── Check if a string is not empty ───────────────────────────


token = get_auth_token() # Returns string or None

if token: # True if token is non-empty string


make_api_call(token)
else:
print("Could not authenticate")

# ── Check if a dict has data ──────────────────────────────────


response_data = [Link]().get("response", {})

if response_data: # True if dict is not empty

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

process(response_data)
else:
print("Empty response")

# ── Default value using or ────────────────────────────────────


hostname = [Link]("hostname") or "unknown-device"
# If get() returns None or "" → use "unknown-device"

# ── None check using truthiness ───────────────────────────────


result = api_call()
if result is not None: # Explicit None check (preferred)
use(result)

if result: # Truthiness check — also catches empty string/list


use(result)

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 8 — Membership (in) & Identity (is) Operators

8.1 in and not in — Membership Testing


# 'in' checks if an item EXISTS in a collection
# Works with: lists, tuples, sets, dicts (checks keys), strings

# ── in with lists ─────────────────────────────────────────────


approved_vendors = ["Cisco", "Juniper", "Arista"]

if "Cisco" in approved_vendors:
print("Approved vendor")

if "Huawei" not in approved_vendors:


print("Vendor not in approved list!")

# ── in with dicts (checks KEYS only!) ────────────────────────


device = {"hostname": "R1", "ip": "[Link]"}

if "ip" in device: # Checks keys


print(f"IP: {device['ip']}")

if "location" not in device:


device["location"] = "Unknown"

# ── in with strings ───────────────────────────────────────────


interface_name = "GigabitEthernet0/0"

if "Gig" in interface_name:
print("This is a Gigabit interface")

if interface_name.startswith("Gig"): # Alternative
print("GigE interface")

# ── in with sets (fastest for large collections!) ─────────────


blocked_ips = {"[Link]", "[Link]", "[Link]"}

client_ip = "[Link]"
if client_ip in blocked_ips: # O(1) — instant even with millions
block_connection(client_ip)

# ── Practical: check multiple values at once ──────────────────


family = [Link]("family")

# Instead of:
if family == "Routers" or family == "Switches" or family == "Wireless":
configure_network_device(device)

# Use in:
if family in ["Routers", "Switches", "Wireless"]:
configure_network_device(device)

# Or with a set (even more Pythonic for pure membership testing):


NETWORK_FAMILIES = {"Routers", "Switches", "Wireless"}
if family in NETWORK_FAMILIES:

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

configure_network_device(device)

8.2 is and is not — Identity Testing


# 'is' checks if two variables point to the EXACT SAME object
# ONLY use 'is' for: None, True, False comparisons

# ── The main use case: checking None ─────────────────────────


token = None
result = get_data()

# Correct — use 'is' for None


if token is None:
print("No token — need to authenticate")

if result is not None:


process(result)

# Wrong — technically works but not Pythonic


if token == None: # Avoid this
print("No token")

# ── Why 'is' instead of == for None? ─────────────────────────


# None is a singleton — there is only ONE None object in Python
# 'is' checks object identity — guaranteed to work
# == could theoretically be overridden by custom classes

# ── Never use 'is' to compare regular values ─────────────────


x = 256
y = 256
print(x is y) # True (Python caches small integers)

x = 1000
y = 1000
print(x is y) # False (large integers not cached — unreliable!)
print(x == y) # True ← always use == for value comparison

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 9 — Nested if Statements

A nested if is an if statement inside another if statement. It lets you check one thing, and then —
only if that passes — check something else.

9.1 Basic Nesting


device = {
"hostname": "R1",
"active": True,
"family": "Routers",
"cpu": 92
}

# Outer check: is device active?


if device["active"]:
print(f"{device['hostname']} is online")

# Inner check (only reached if device is active)


if device["family"] == "Routers":
print(" This is a router")

# Deeper check (only reached if router)


if device["cpu"] > 90:
print(" ALERT: Router CPU is critical!")
else:
print(" Router CPU is normal")

elif device["family"] == "Switches":


print(" This is a switch")

else:
print(f"{device['hostname']} is offline — skipping all checks")

9.2 Flattening Nested Conditions — Best Practice


# Deep nesting is hard to read. Flatten it using:
# 1. Guard clauses (early return)
# 2. and/or operators
# 3. elif instead of nested if

# ── BAD: deeply nested (hard to read) ────────────────────────


def process_bad(device):
if device is not None:
if [Link]("active"):
if [Link]("reachabilityStatus") == "Reachable":
if [Link]("cpu", 0) < 90:
print(f"Processing {device['hostname']}")
else:
print("CPU too high")

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

else:
print("Unreachable")
else:
print("Inactive")
else:
print("No device data")

# ── GOOD: guard clauses (flat, easy to read) ─────────────────


def process_good(device):
# Check preconditions early and return
if device is None:
print("No device data")
return

if not [Link]("active"):
print(f"{[Link]('hostname','?')} is inactive — skipping")
return

if [Link]("reachabilityStatus") != "Reachable":
print(f"{device['hostname']} is unreachable — skipping")
return

if [Link]("cpu", 0) >= 90:


print(f"{device['hostname']} CPU too high — skipping")
return

# If we get here, all checks passed


print(f"Processing {device['hostname']}")
apply_config(device)

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 10 — Ternary (One-Line) Conditions

The ternary operator lets you write a simple if/else on a single line. It is great for assigning
values or building strings based on a condition.

10.1 Syntax and Basic Usage


# Syntax:
# value_if_true if condition else value_if_false
#
# Read it as: "give me X if condition is true, otherwise give me Y"

status_code = 200

# Normal way (3 lines)


if status_code == 200:
result = "Success"
else:
result = "Failed"

# Ternary way (1 line — same result)


result = "Success" if status_code == 200 else "Failed"
print(result) # Success

# ── More examples ─────────────────────────────────────────────


active = True
status = "UP" if active else "DOWN"
print(status) # UP

cpu = 85
label = "HIGH" if cpu > 80 else "NORMAL"

# In an f-string
print(f"Device is {'active' if active else 'inactive'}")

# With icons
icon = "✅" if active else "❌"
print(f"{icon} Router1")

10.2 Ternary in DevNet — Practical Uses


devices = [
{"hostname": "R1", "active": True, "cpu": 92},
{"hostname": "SW1", "active": False, "cpu": 0},
{"hostname": "FW1", "active": True, "cpu": 45},
]

# ── In a loop — build status strings ─────────────────────────


for d in devices:
status = "UP" if d["active"] else "DOWN"

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

cpu_label = "HIGH" if d["cpu"] > 80 else "OK"


icon = "🔴" if not d["active"] else ("🟡" if d["cpu"] > 80 else "🟢")
print(f" {icon} {d['hostname']:<10} {status:<6} CPU: {cpu_label}")

# ── In a list comprehension ───────────────────────────────────


statuses = ["UP" if d["active"] else "DOWN" for d in devices]
print(statuses) # ['UP', 'DOWN', 'UP']

# ── As a function argument ────────────────────────────────────


log_level = "ERROR" if response.status_code >= 400 else "INFO"
log(log_level, f"API call returned {response.status_code}")

# ── Setting a default ─────────────────────────────────────────


hostname = [Link]("hostname")
display_name = hostname if hostname else "Unknown Device"

When NOT to Use Ternary


Do not use ternary for complex logic — it becomes unreadable.
Never nest ternary operators: x if a else y if b else z ← confusing!
If you need multiple conditions or complex logic, use regular if/elif/else.
Rule: ternary is for simple two-option assignments only.

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 11 — match / case (Python 3.10+)

Python 3.10 introduced match/case — a cleaner way to write conditions when you are checking
one variable against many specific values. It is like a switch statement from other languages but
much more powerful.

11.1 Basic match / case Syntax


# Syntax:
# match variable:
# case value1:
# ...
# case value2:
# ...
# case _: ← underscore = default (like else)
# ...

status_code = 404

match status_code:
case 200:
print("OK — Success")
case 201:
print("Created")
case 204:
print("No Content")
case 401:
print("Unauthorized")
case 403:
print("Forbidden")
case 404:
print("Not Found") # ← this runs
case 500:
print("Server Error")
case _: # default — matches anything
print(f"Unknown: {status_code}")

11.2 match / case with Guards and OR patterns


family = "Switches"

# OR pattern — multiple values in one case


match family:
case "Routers":
print("Configure routing protocols")
case "Switches" | "Wireless": # | means OR
print("Configure VLANs and access ports")
case "Security" | "Firewall":
print("Configure security policies")
case _:

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

print(f"Unknown family: {family}")

# Guard (if clause inside case)


cpu = 92
match cpu:
case c if c >= 90:
print(f"CRITICAL: CPU at {c}%")
case c if c >= 70:
print(f"WARNING: CPU at {c}%")
case c if c >= 50:
print(f"MODERATE: CPU at {c}%")
case _:
print("CPU OK")

match/case vs if/elif
Use if/elif for: range checks (>= 80), complex conditions, comparing multiple variables.
Use match/case for: comparing ONE variable against many exact values (cleaner, more readable).
match/case requires Python 3.10+. Check with: python3 --version

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 12 — Complete DevNet Examples

This section shows complete, real-world examples of conditions in action, combining everything
from this guide.

12.1 Complete API Response Handler


import requests, time

def call_api(url, headers, retries=3):


"""Call an API with retry logic and full condition handling."""

for attempt in range(1, retries + 1):


print(f"Attempt {attempt}/{retries}: GET {url}")

try:
response = [Link](url, headers=headers,
timeout=10, verify=False)
except [Link]:
print(" ERROR: Cannot connect — check network/IP")
if attempt < retries:
[Link](2)
continue
return None
except [Link]:
print(" ERROR: Request timed out")
if attempt < retries:
[Link](2)
continue
return None

# ── Condition block: handle every HTTP status code ────


if response.status_code == 200:
print(" SUCCESS")
return [Link]()

elif response.status_code == 201:


print(" CREATED")
return [Link]()

elif response.status_code == 204:


print(" SUCCESS — no content")
return {}

elif response.status_code == 401:


print(" UNAUTHORIZED — token may be expired")
return None # Caller must re-auth

elif response.status_code == 403:


print(" FORBIDDEN — check user permissions")
return None # No point retrying

elif response.status_code == 404:

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

print(f" NOT FOUND — URL may be wrong: {url}")


return None # No point retrying

elif response.status_code == 429:


wait = int([Link]("Retry-After", 5))
print(f" RATE LIMITED — waiting {wait}s before retry")
[Link](wait)
continue # Retry

elif 500 <= response.status_code <= 599:


print(f" SERVER ERROR {response.status_code} — retrying...")
if attempt < retries:
[Link](3)
continue
return None

else:
print(f" UNEXPECTED STATUS: {response.status_code}")
return None

print("All attempts exhausted")


return None

12.2 Device Configuration Router


def configure_device(device):
"""Apply the right configuration based on device properties."""

# ── Guard clauses — check preconditions first ─────────────


if device is None:
print("ERROR: No device data provided")
return False

hostname = [Link]("hostname", "unknown")

if not [Link]("active", False):


print(f"SKIP: {hostname} is inactive")
return False

if [Link]("reachabilityStatus") != "Reachable":
print(f"SKIP: {hostname} is not reachable")
return False

# ── Main logic: route by device family ────────────────────


family = [Link]("family", "Unknown")

if family == "Routers":
# Router-specific checks
os_version = [Link]("softwareVersion", "")
if os_version.startswith("17"):
print(f" {hostname}: Applying IOS-XE 17.x router config")
apply_iosxe_router_config(device)
elif os_version.startswith("16"):
print(f" {hostname}: Applying IOS-XE 16.x router config")
apply_legacy_router_config(device)
else:
print(f" {hostname}: Unknown OS version '{os_version}' — manual
review needed")
return False

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

elif family == "Switches":


port_count = int([Link]("portCount", 0))
if port_count >= 48:
print(f" {hostname}: Applying 48-port switch config")
elif port_count >= 24:
print(f" {hostname}: Applying 24-port switch config")
else:
print(f" {hostname}: Applying small switch config ({port_count}
ports)")
apply_switch_config(device)

elif family in ("Security", "Firewalls"):


print(f" {hostname}: Firewall — manual configuration required")
create_ticket(hostname, "Firewall config review needed")
return False

elif family == "Wireless":


print(f" {hostname}: Applying wireless AP config")
apply_wireless_config(device)

else:
print(f" {hostname}: Unknown family '{family}' — skipping")
return False

print(f" {hostname}: Configuration completed successfully")


return True

12.3 Data Validation with Conditions


def validate_device_data(data):
"""Validate device data before processing. Returns (ok, errors)."""
errors = []

# ── Check required fields ─────────────────────────────────


required = ["hostname", "ip", "family"]
for field in required:
if field not in data:
[Link](f"Missing required field: '{field}'")
elif not data[field]: # Empty string, None, 0
[Link](f"Field '{field}' is empty")

if errors: # Stop early if required fields missing


return False, errors

# ── Validate hostname ─────────────────────────────────────


hostname = data["hostname"]
if not isinstance(hostname, str):
[Link]("hostname must be a string")
elif len(hostname) < 2:
[Link]("hostname too short (min 2 chars)")
elif len(hostname) > 64:
[Link]("hostname too long (max 64 chars)")

# ── Validate IP address ───────────────────────────────────


ip = [Link]("ip", "")
parts = [Link](".")
if len(parts) != 4:
[Link](f"Invalid IP format: {ip}")

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

else:
for part in parts:
if not [Link]() or not (0 <= int(part) <= 255):
[Link](f"Invalid IP octet in: {ip}")
break

# ── Validate family ───────────────────────────────────────


valid_families = {"Routers", "Switches", "Wireless", "Security"}
if data["family"] not in valid_families:
[Link](f"Unknown family: '{data['family']}'")

return len(errors) == 0, errors

# Usage
device = {"hostname": "R1", "ip": "[Link]", "family": "Routers"}
ok, errors = validate_device_data(device)

if ok:
print(f"Validation passed — processing {device['hostname']}")
configure_device(device)
else:
print("Validation FAILED:")
for error in errors:
print(f" - {error}")

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Part 13 — Common Mistakes & Cheat Sheet

13.1 Top 10 Condition Mistakes


# Mistake Wrong Correct
1 = instead of == for if x = 5: if x == 5:
comparison
2 Missing colon after if x == 5 if x == 5:
if/elif/else
3 Wrong indentation if x: \nprint(x) if x:\n print(x)
4 == instead of is for None if x == None: if x is None:
5 Checking float equality if 0.1+0.2 == 0.3: if [Link](0.1+0.2, 0.3):
with ==
6 Wrong elif order (too broad elif x >= 50 before >= 80 Put specific (>= 80) before broad (>=
first) 50)
7 Deep nesting instead of if a: if b: if c: Use guard clauses with early return
guards
8 Comparing to True/False if active == True: if active:
explicitly
9 Not normalising string if family == 'routers': if [Link]() == 'routers':
case
1 Over-complex ternary x if a else y if b else z Use regular if/elif/else instead
0

13.2 Complete Conditions Cheat Sheet


Pattern Code Example
Basic if if condition: \n do_something()
if / else if condition: else:
if / elif / else if c1: elif c2: elif c3: else:
Equal to if x == 5:
Not equal if x != 5:
Greater / Less if x > 5: if x < 5:
Greater or equal if x >= 5: if x <= 5:
Chained comparison if 1 <= x <= 100:

Python Notes for Network Automation — DevNet Study Guide


Python Deep Dive – Conditions: if, elif & else CCNA DevNet 200-901

Pattern Code Example


and — both true if a > 0 and b > 0:
or — at least one true if a > 0 or b > 0:
not — invert if not active:
Check None if x is None: if x is not None:
Check truthy if token: (True if non-empty/non-zero)
Check falsy if not token: (True if empty/None/0)
Membership in list if x in ["a", "b", "c"]:
Not in list if x not in blocked_list:
Key in dict if "key" in my_dict:
Substring in string if "Gig" in interface_name:
Starts/ends with if [Link]('Gi'): [Link]('0'):
Ternary assignment status = "UP" if active else "DOWN"
Ternary in f-string f"State: {'on' if active else 'off'}"
Default with or name = [Link]("hostname") or "unknown"
Guard clause if not condition: return
Multiple values if family in {"Routers", "Switches"}:
match/case (3.10+) match status: case 200: case _:

Master conditions — write smarter, safer automation!


Python Deep Dive — Conditions — CCNA DevNet Associate 200-901

Python Notes for Network Automation — DevNet Study Guide

You might also like