DEV Community

Tejas Shinkar
Tejas Shinkar

Posted on

String Methods, Conditional Statements (if/elif/else), Loops (for, range())

šŸ Python for DevOps — Class 5 Notes

Topic: String Methods, Conditional Statements (if/elif/else), Loops (for, range())


šŸ“Œ Key Concepts Overview

Concept One-Line Definition
String Methods Built-in functions to inspect and transform strings
if / elif / else Execute code blocks based on conditions
for loop Iterate over any iterable — string, list, range, dict
range() Generate a sequence of numbers to loop over
Nested if An if block inside another if block
Nested for A for loop inside another for loop

šŸ”¤ Part 1 — String Methods (Continuation from Class 4)

Checking String Case

# islower() — True if ALL characters are lowercase
'devops'.islower()     # True
'Devops'.islower()     # False

# isupper() — True if ALL characters are uppercase
'DEVOPS'.isupper()     # True
'Devops'.isupper()     # False

# Practical: normalize before comparing
env = input('Enter environment: ')
if env.lower() == 'production':
    print('āš ļø Deploying to PROD!')
Enter fullscreen mode Exit fullscreen mode

Checking Digit / Numeric Strings

Method Accepts Rejects DevOps Use
isdecimal() 0-9 only decimals, superscripts Port validation
isdigit() 0-9 + superscripts decimal points Version numbers
isnumeric() 0-9 + superscripts + fractions decimal points Broadest check
# Key difference — decimal point breaks all three
'8080'.isdecimal()    # True
'8080'.isdigit()      # True
'8080'.isnumeric()    # True

'80.80'.isdecimal()   # False — dot is not a digit
'80.80'.isdigit()     # False
'80.80'.isnumeric()   # False

# DevOps use: validate user input before casting
port_input = input('Enter port: ')
if port_input.isdecimal():
    port = int(port_input)
else:
    print('āŒ Invalid port — must be a whole number')
Enter fullscreen mode Exit fullscreen mode

replace() — Find and Replace in Strings

# str.replace('old', 'new')
'Python'.replace('P', 'J')              # 'Jython'
'prod-server-01'.replace('-', '_')      # 'prod_server_01'
'This is python class'.replace('i','a') # 'Thas as python class' — ALL occurrences

# DevOps: sanitize strings for use in AWS resource names (no spaces allowed)
resource_name = 'my resource name'
safe_name = resource_name.replace(' ', '-')  # 'my-resource-name'

# Remove spaces entirely
'Pyt hon'.replace(' ', '')    # 'Python'
Enter fullscreen mode Exit fullscreen mode

startswith() / endswith()

log_line = 'ERROR: Connection refused on port 5432'

# Route logs based on prefix
if log_line.startswith('ERROR'):
    print('🚨 Alert triggered')
elif log_line.startswith('WARN'):
    print('āš ļø Warning logged')

# Check file types
filename = 'deploy.sh'
if filename.endswith('.sh'):
    print('Shell script — set execute permission')
elif filename.endswith('.py'):
    print('Python script')
elif filename.endswith('.tf'):
    print('Terraform file')
Enter fullscreen mode Exit fullscreen mode

šŸ”€ Part 2 — Conditional Statements

if — Single Condition

# if condition:
#     block runs only when condition is True
# (anything outside the block always runs)

a = 392
if a % 2 == 0:
    print('Even')        # runs only if condition True

print('Done')            # ALWAYS runs — outside if block

# āš ļø Common mistake from class:
# Putting "Number is odd" OUTSIDE the if block
# It prints even when number is even — logic bug
Enter fullscreen mode Exit fullscreen mode

if-else — Two Branches

# if condition:
#     runs when True
# else:
#     runs when False

a = int(input('Enter a number: '))
if a % 2 == 0:
    print('Even')
else:
    print('Odd')

# DevOps: health check routing
status_code = 200
if status_code == 200:
    print('āœ… Service healthy')
else:
    print(f'āŒ Service unhealthy — code: {status_code}')
Enter fullscreen mode Exit fullscreen mode

Multiple if vs if-elif-else — Critical Difference

# āŒ Multiple if — checks ALL conditions independently (inefficient)
a = 1
if a == 1: print('One')      # matches — prints One
if a == 2: print('Two')      # checks anyway — no match
if a == 3: print('Three')    # checks anyway — no match
# All 5 conditions are evaluated even after a match

# āœ… if-elif-else — stops at FIRST match (efficient)
if a == 1:
    print('One')             # matches — STOPS here
elif a == 2:
    print('Two')             # SKIPPED
elif a == 3:
    print('Three')           # SKIPPED
else:
    print('Out of range')    # SKIPPED
Enter fullscreen mode Exit fullscreen mode

Rule of thumb: Use elif when conditions are mutually exclusive (only one can be true). Use multiple if when you need to check all conditions independently.

if-elif-else — Full Pattern

# HTTP status code handler (real DevOps pattern)
status = int(input('Enter HTTP status code: '))

if status == 200:
    print('OK — Success')
elif status == 201:
    print('Created — Resource provisioned')
elif status == 400:
    print('Bad Request — Check input params')
elif status == 401:
    print('Unauthorized — Check IAM/credentials')
elif status == 403:
    print('Forbidden — Check permissions')
elif status == 404:
    print('Not Found — Resource missing')
elif status == 500:
    print('Internal Server Error — Check app logs')
else:
    print(f'Unknown status: {status}')
Enter fullscreen mode Exit fullscreen mode

in Operator with Conditionals

# Check membership — works on strings, lists, tuples, sets, dicts
x = input('Enter a letter: ')

if x.lower() in 'aeiou':
    print('Vowel')
else:
    print('Consonant')

# DevOps: check if region is valid
region = input('Enter AWS region: ')
valid_regions = ['ap-south-1', 'us-east-1', 'eu-west-1']
if region in valid_regions:
    print('āœ… Valid region')
else:
    print('āŒ Invalid region')
Enter fullscreen mode Exit fullscreen mode

Nested if-else

# When you need to check conditions inside conditions
# Class used: pass Python AND Linux AND AWS to clear exam

p = int(input('Python score: '))
l = int(input('Linux score: '))
a = int(input('AWS score: '))

if p > 75:
    if l > 75:
        if a > 75:
            print('āœ… Cleared all subjects')
        else:
            print('āŒ Work hard in AWS')
    else:
        print('āŒ Work hard in Linux')
else:
    print('āŒ Work hard in Python')

# DevOps equivalent: multi-condition deployment gate
cpu = 45
memory = 70
disk = 60

if cpu < 80:
    if memory < 85:
        if disk < 90:
            print('āœ… All checks passed — safe to deploy')
        else:
            print('āŒ Disk usage too high')
    else:
        print('āŒ Memory usage too high')
else:
    print('āŒ CPU usage too high')
Enter fullscreen mode Exit fullscreen mode

šŸ” Part 3 — Loops

for Loop — Iterating Over Iterables

# Syntax: for variable in iterable:
#             block

# Iterables: string, list, tuple, set, dict, range, bytes

# Over a string — character by character
for char in 'Python':
    print(char)     # P y t h o n (each on new line)

# Over a list
servers = ['web-01', 'db-01', 'cache-01']
for server in servers:
    print(f'Pinging {server}...')

# Over a list with condition
for server in servers:
    if server.startswith('db'):
        print(f'āš ļø Database server: {server}')
Enter fullscreen mode Exit fullscreen mode

range() — Generating Number Sequences

# range(stop)          → 0 to stop-1
# range(start, stop)   → start to stop-1
# range(start, stop, step) → with step size

range(10)           # 0, 1, 2, ..., 9
range(1, 11)        # 1, 2, ..., 10
range(0, 51, 2)     # 0, 2, 4, ..., 50  (even numbers)
range(-1, -7, -1)   # -1, -2, ..., -6  (reverse traversal)

# Common patterns
for i in range(10):
    print('DevOps')     # print 10 times

for i in range(1, 51):
    if i % 2 == 0:
        print(i)        # even numbers 2-50
Enter fullscreen mode Exit fullscreen mode

Looping with Index — range(len())

# When you need BOTH the index and the value
str1 = 'Python'
for i in range(len(str1)):
    print(i, str1[i])
# 0 P
# 1 y
# 2 t
# 3 h
# 4 o
# 5 n

# Find all positions of a character
log = 'ERROR: disk full. ERROR: retry failed.'
for i in range(len(log)):
    if log[i] == 'E' and log[i:i+5] == 'ERROR':
        print(f'ERROR found at index {i}')
Enter fullscreen mode Exit fullscreen mode

String + Loop Patterns

# Extract vowels from a string
str1 = 'wqciecneucqbcjeqbviuqciwqnkeqnv'
for char in str1:
    if char.upper() in 'AEIOU':
        print(char)

# Get all uppercase letters
str1 = 'This is Python Class.'
for char in str1:
    if char.isupper():
        print(char)    # T, P, C

# Reverse a string using loop
str1 = 'Python'
rev_str = ''
for i in range(-1, -len(str1)-1, -1):
    rev_str += str1[i]
print(rev_str)         # nohtyP
Enter fullscreen mode Exit fullscreen mode

Nested for Loops

# Loop inside a loop — inner loop completes FULLY for each outer iteration

# Class example: print each word AND each character
lst = ['Peter', 'piper', 'picked']

for word in lst:
    print(word)
    for char in word:
        print(char)

# DevOps: scan all servers for all ports
servers = ['web-01', 'db-01']
ports = [22, 80, 443]

for server in servers:
    for port in ports:
        print(f'Checking {server}:{port}')
# web-01:22, web-01:80, web-01:443, db-01:22 ...
Enter fullscreen mode Exit fullscreen mode

ā˜ļø DevOps / Cloud Use Cases

# 1. Log line parser — classify log levels
logs = [
    'ERROR: DB connection failed',
    'INFO: Deployment started',
    'WARN: CPU at 82%',
    'ERROR: Pod CrashLoopBackOff',
]

for log in logs:
    if log.startswith('ERROR'):
        print(f'🚨 ALERT: {log}')
    elif log.startswith('WARN'):
        print(f'āš ļø  WARN: {log}')
    else:
        print(f'ā„¹ļø  INFO: {log}')

# 2. Port scanner stub (basic)
target_ports = [22, 80, 443, 3306, 5432, 8080, 8443]
for port in target_ports:
    if port in [22, 80, 443]:
        print(f'Port {port} — standard, expected open')
    elif port in [3306, 5432]:
        print(f'Port {port} — DB port, should be private!')
    else:
        print(f'Port {port} — verify if needed')

# 3. Multi-region health check
regions = ['ap-south-1', 'us-east-1', 'eu-west-1']
for region in regions:
    if region.startswith('ap'):
        print(f'{region} → APAC cluster')
    elif region.startswith('us'):
        print(f'{region} → US cluster')
    else:
        print(f'{region} → EU cluster')

# 4. Validate resource name before creating
name = input('Enter resource name: ')
safe_name = name.replace(' ', '-').lower()
if safe_name.replace('-', '').isalnum():
    print(f'āœ… Valid name: {safe_name}')
else:
    print('āŒ Name has invalid characters')

# 5. Find ERROR count in a log file (simulated)
log_data = 'INFO start\nERROR timeout\nINFO retry\nERROR disk full\nINFO done'
error_count = 0
for line in log_data.split('\n'):
    if line.startswith('ERROR'):
        error_count += 1
print(f'Total errors: {error_count}')
Enter fullscreen mode Exit fullscreen mode

āŒ Common Mistakes

Mistake Code Fix
Code outside if always runs print('Odd') after the if block Put it inside else
Multiple if instead of elif All conditions check even after match Use elif for exclusive branches
range(10) gives 0–9, not 1–10 range(10) → 0,1...9 range(1, 11) for 1 to 10
Off-by-one in reverse range range(-1, -6, -1) for 6-char string range(-1, -len(s)-1, -1)
in on wrong type if port in '8080' → checks substring in string if port in [8080, 443] — use a list
islower() on string with spaces 'hello world'.islower() → True Spaces are ignored — only letters checked
Forgetting colon after if/for if x == 1 → SyntaxError Always end with :
Wrong indentation Mixed tabs/spaces Use 4 spaces consistently

šŸŽÆ Interview Points

  1. "Difference between if-elif and multiple if statements?"
    → elif stops after the first match — faster, mutually exclusive. Multiple if evaluates every condition every time.

  2. "What is the difference between isdecimal(), isdigit(), isnumeric()?"
    → isdecimal() is strictest (0-9 only). isdigit() also accepts superscripts. isnumeric() is broadest — accepts fractions too. In DevOps, use isdecimal() for port/number validation.

  3. "How does for loop work internally?"
    → Python calls iter() on the iterable, then repeatedly calls next() until StopIteration. Every for loop is really an iterator under the hood.

  4. "What does range(1, 10) return?"
    → 1 through 9 — stop value is excluded. range(1, 11) for 1 through 10.

  5. "When would you use nested loops in DevOps?"
    → Scanning multiple servers Ɨ multiple ports. Processing multi-dimensional data. Parsing nested config structures.

  6. "Can you use in with a dict?"
    → in on a dict checks keys only, not values. 'key' in my_dict → checks keys.

  7. "What is the in operator?"
    → Membership test — returns True if element exists in the iterable. Works on strings, lists, tuples, sets, dict keys.


šŸ“š Knowledge Base — Quick Revision

# ── STRING METHODS ──────────────────────────────────────────
'devops'.islower()              # True
'DEVOPS'.isupper()              # True
'8080'.isdecimal()              # True  ← use for port validation
'8.0'.isdecimal()               # False ← dot breaks it
'hello'.replace('l', 'r')       # 'herro'
'error.log'.endswith('.log')    # True
'ERROR'.startswith('ERR')       # True

# ── CONDITIONALS ────────────────────────────────────────────
if condition:
    ...
elif condition:         # else-if — stops at first match
    ...
else:
    ...

# Use 'in' for membership
if value in [list, of, options]:
    ...

# ── FOR LOOP ────────────────────────────────────────────────
for item in iterable:       # iterates over elements
    ...

for i in range(10):         # 0 to 9
    ...

for i in range(1, 11):      # 1 to 10
    ...

for i in range(0, 10, 2):   # 0,2,4,6,8 (step=2)
    ...

for i in range(len(s)):     # index-based traversal
    print(i, s[i])

# ── NESTED LOOPS ────────────────────────────────────────────
for server in servers:
    for port in ports:
        print(f'{server}:{port}')

# ── STRING REVERSE ───────────────────────────────────────────
rev = ''
for i in range(-1, -len(s)-1, -1):
    rev += s[i]
# or simply: s[::-1]
Enter fullscreen mode Exit fullscreen mode

šŸ‹ļø Practice Questions

Easy

  1. Write a script that checks if a given string (like a resource name) contains only lowercase letters using islower(). If not, convert it and print the result.
  2. Use a for loop with range() to print all even numbers from 1 to 100.
  3. Take a filename as input (e.g., deploy.sh, main.tf, config.yml). Use endswith() to print what type of file it is.

Medium

  1. Write a script that takes a port number string as input, validates it using isdecimal(), casts it to int, and checks if it falls in one of these ranges: Well-known (0–1023), Registered (1024–49151), Dynamic (49152–65535). Print the category.
  2. Given a log string like 'INFO start\nERROR timeout\nWARN disk 80%\nERROR crash', loop through each line and count how many are ERROR, WARN, and INFO. Print the counts.
  3. Write a script that builds a "safe" AWS resource name from user input: strip spaces with replace(), convert to lowercase, validate with isdecimal() / isalnum(), and print either the safe name or an error.

DevOps-Focused

  1. Deployment Gate Script: Ask the user for CPU %, memory %, and disk % (all integers). Use nested if-else to decide: if all are under 80%, print "āœ… Safe to deploy". If any one exceeds, print which resource is the bottleneck. Use f-strings for output.
  2. Log Analyzer: Given this list of log lines:
   logs = ['ERROR: pod crash', 'INFO: deploy started', 'ERROR: OOM killed',
           'WARN: cpu spike', 'INFO: rollback complete', 'ERROR: disk full']
Enter fullscreen mode Exit fullscreen mode

Loop through and: (a) print ERROR lines in uppercase using .upper(), (b) count total errors, (c) print a final summary: "Found X errors in Y total log lines".


Top comments (0)