ๆƒฏๆ€ง่šๅˆ ้ซ˜ๆ•ˆ่ฟฝ่ธชๅ’Œ้˜…่ฏปไฝ ๆ„Ÿๅ…ด่ถฃ็š„ๅšๅฎขใ€ๆ–ฐ้—ปใ€็ง‘ๆŠ€่ต„่ฎฏ
้˜…่ฏปๅŽŸๆ–‡ ๅœจๆƒฏๆ€ง่šๅˆไธญๆ‰“ๅผ€

ๆŽจ่่ฎข้˜…ๆบ

F
Full Disclosure
V
Vulnerabilities โ€“ Threatpost
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
SecWiki News
SecWiki News
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
B
Blog
TaoSecurity Blog
TaoSecurity Blog
The Last Watchdog
The Last Watchdog
H
Hacker News: Front Page
Hacker News - Newest:
Hacker News - Newest: "LLM"
ๅš
ๅšๅฎขๅ›ญ_้ฆ–้กต
D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Y
Y Combinator Blog
W
WeLiveSecurity
N
News and Events Feed by Topic
F
Fortinet All Blogs
PCI Perspectives
PCI Perspectives
WordPressๅคงๅญฆ
WordPressๅคงๅญฆ
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
Forbes - Security
Forbes - Security
T
Tailwind CSS Blog
Hacker News: Ask HN
Hacker News: Ask HN
็ˆฑ่Œƒๅ„ฟ
็ˆฑ่Œƒๅ„ฟ
่…พ
่…พ่ฎฏCDC
Last Week in AI
Last Week in AI
ๆœˆๅ…‰ๅšๅฎข
ๆœˆๅ…‰ๅšๅฎข
C
Cybersecurity and Infrastructure Security Agency CISA
P
Proofpoint News Feed
Help Net Security
Help Net Security
V
V2EX
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
H
Heimdal Security Blog
L
LINUX DO - ๆœ€ๆ–ฐ่ฏ้ข˜
GbyAI
GbyAI
The Hacker News
The Hacker News
็ฝ—
็ฝ—็ฃŠ็š„็‹ฌ็ซ‹ๅšๅฎข
S
SegmentFault ๆœ€ๆ–ฐ็š„้—ฎ้ข˜
H
Hackread โ€“ Cybersecurity News, Data Breaches, AI and More
ๅš
ๅšๅฎขๅ›ญ - ใ€ๅฝ“่€็‰นใ€‘
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V2EX - ๆŠ€ๆœฏ
V2EX - ๆŠ€ๆœฏ
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
O
OpenAI News
OSCHINA ็คพๅŒบๆœ€ๆ–ฐๆ–ฐ้—ป
OSCHINA ็คพๅŒบๆœ€ๆ–ฐๆ–ฐ้—ป

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Donโ€™t Fail โ€” They Drift Spilling beans for how i learn for exam๐Ÿ˜"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" โ€” What Actually Happened Comfy Cloudโ€™s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions โ€” here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components โ€” Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cรณmo construรญ un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 ๐Ÿš€ I Built an Ethical Hacking Scanner Tool โ€“ Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points โ€” Here's What I Found About How Markets Really Move EcoTrack AI โ€” Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead โ€” I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve โ€” no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like Youโ€™re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace โ€” how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025โ€“62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D โ€” A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent โ€” It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly โ€” 2026/04/10โ€“04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI ้€ฑๅ ฑ โ€” 2026/04/10โ€“2026/04/17 ๆจกๅž‹ๅฐ้Ž–ๆฝฎไพ†ไบ†๏ผŒไฝ†ๅทฅๅ…ท้ˆๆ‰ๆ˜ฏ็œŸๆˆฐๅ ด Maybe this is how Open-Source apps are born... ๐Ÿš€ Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge โ€” $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase โ€” Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train โ€” Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extraรงรฃo de Vรญdeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life โ€” Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 โ€” Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows โ€” Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTrackingๅฎ‰่ฃ…ๅ’ŒiPhone้ขๆ•้…็ฝฎๆ•™็จ‹๏ผŒๆœ‰bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
String Methods, Conditional Statements (if/elif/else), Loops (for, range())
Tejas Shinkar ยท 2026-06-19 ยท via DEV Community

๐Ÿ 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

  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]


๐Ÿ‹๏ธ 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']

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".