๐ 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!')
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')
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'
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')
๐ 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
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}')
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
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}')
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')
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')
๐ 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}')
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
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}')
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
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 ...
โ๏ธ 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}')
โ 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
"Difference between
if-elifand multipleifstatements?"
โelifstops after the first match โ faster, mutually exclusive. Multipleifevaluates every condition every time."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, useisdecimal()for port/number validation."How does
forloop work internally?"
โ Python callsiter()on the iterable, then repeatedly callsnext()untilStopIteration. Everyforloop is really an iterator under the hood."What does
range(1, 10)return?"
โ 1 through 9 โ stop value is excluded.range(1, 11)for 1 through 10."When would you use nested loops in DevOps?"
โ Scanning multiple servers ร multiple ports. Processing multi-dimensional data. Parsing nested config structures."Can you use
inwith a dict?"
โinon a dict checks keys only, not values.'key' in my_dictโ checks keys."What is the
inoperator?"
โ Membership test โ returnsTrueif 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]
๐๏ธ Practice Questions
Easy
- 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. - Use a
forloop withrange()to print all even numbers from 1 to 100. - Take a filename as input (e.g.,
deploy.sh,main.tf,config.yml). Useendswith()to print what type of file it is.
Medium
- Write a script that takes a port number string as input, validates it using
isdecimal(), casts it toint, and checks if it falls in one of these ranges: Well-known (0โ1023), Registered (1024โ49151), Dynamic (49152โ65535). Print the category. - Given a log string like
'INFO start\nERROR timeout\nWARN disk 80%\nERROR crash', loop through each line and count how many areERROR,WARN, andINFO. Print the counts. - Write a script that builds a "safe" AWS resource name from user input: strip spaces with
replace(), convert to lowercase, validate withisdecimal()/isalnum(), and print either the safe name or an error.
DevOps-Focused
-
Deployment Gate Script: Ask the user for CPU %, memory %, and disk % (all integers). Use nested
if-elseto 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. - 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']
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".

























