š 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".
Top comments (0)