Variables, Data Types, Operators & Strings
This is where Python actually begins. Variables let you store information. Data types tell Python what kind of information it’s dealing with. Operators let you work with it. And strings โ well, you’ll use strings in almost every program you ever write. These four concepts are the foundation of everything else in this course.
Variables & Assignment
A variable is just a name you give to a piece of information so you can use it later. That’s it. Think of it like labelling a box โ you put something inside and stick a label on the outside so you can find it again.
In Python, creating a variable is called assignment. You write the name you want, then an equals sign, then the value. Python figures out the type automatically โ you don’t have to declare it in advance the way some other languages make you.
Variable names follow a few rules. They can contain letters, numbers, and underscores. They cannot start with a number. They are case-sensitive โ Server and server are two different variables. By convention, Python programmers use snake_case: all lowercase with underscores between words. So server_name, not ServerName or servername.
Data Types: int, float, str, bool
Python has several built-in types to represent different kinds of information. The four you’ll use most in this course are integers, floats, strings, and booleans.
Integer (int) โ whole numbers, positive or negative. No decimal point. You use these for counts, IDs, port numbers, quantities. ticket_count = 47
Float (float) โ numbers with a decimal point. CPU usage percentages, response times, currency amounts. cpu_usage = 73.4
String (str) โ text. Anything wrapped in single or double quotes is a string. Usernames, server names, file paths, email addresses, error messages. hostname = “db-server-01”
Boolean (bool) โ either True or False. Nothing else. These are Python’s way of representing yes/no, on/off, success/failure. You’ll use them heavily in control flow (Module 2). is_connected = True
Type Conversion
Python doesn’t automatically mix types for you. You can’t add a number to a string โ Python will refuse and throw an error. This is a feature, not a bug. It stops a lot of subtle mistakes from slipping through unnoticed.
When you need to switch between types, you do it explicitly using conversion functions: int(), float(), and str(). This comes up constantly in real work โ reading a number from a file, parsing command-line input, or building a log message that mixes text and numbers.
Operators
Operators are the symbols Python uses to perform operations on data. There are four groups worth knowing at this stage.
Arithmetic operators work on numbers: + add, – subtract, * multiply, / divide, // integer division (no remainder), % modulo (remainder only), ** power.
Comparison operators compare two values and return True or False: == equal, != not equal, > greater than, < less than, >= and <= for the inclusive versions.
Logical operators combine boolean expressions: and, or, not. You’ll use these constantly in if-statements.
Assignment operators are shortcuts for updating a variable: x += 5 is the same as x = x + 5. Similarly -=, *=, /=.
String Methods
Strings in Python aren’t just passive text โ they come with built-in methods you can call on them. A method is just a function that belongs to a specific type. You call it by putting a dot after your variable name, then the method name and parentheses.
In corporate work, you’ll constantly deal with text: server names, email addresses, log entries, error messages, user input, file names. String methods let you clean, transform, search, and extract from all of that without writing loops yourself.
f-Strings & String Formatting
f-strings are the modern, clean way to put variables inside strings. The “f” stands for “formatted”. You put an f before the opening quote, and then anywhere inside the string where you want to insert a variable, you wrap it in curly braces.
Before f-strings existed (pre-Python 3.6), people used .format() or % formatting. You’ll still see those in older code. But for anything you write from scratch, use f-strings โ they’re cleaner, easier to read, and support inline expressions.
Variables & assignment
# Basic assignment
server_name = "prod-db-01" # str
ticket_count = 47 # int
cpu_usage = 73.4 # float
is_online = True # bool
# Multiple assignment on one line
host, port, timeout = "localhost", 5432, 30
# Reassigning a variable
ticket_count = 48 # now 48
ticket_count += 1 # shorthand: now 49
# Check the type of any variable
print(type(server_name)) # <class 'str'>
print(type(ticket_count)) # <class 'int'>
print(type(cpu_usage)) # <class 'float'>
print(type(is_online)) # <class 'bool'>
Type conversion
# str โ int / float
port_str = "5432"
port_int = int(port_str) # 5432 (integer)
usage_str = "73.4"
usage_float = float(usage_str) # 73.4 (float)
# int / float โ str (needed when building messages)
count = 12
message = "Open tickets: " + str(count) # "Open tickets: 12"
# int โ float
int(73.9) # 73 โ truncates, does NOT round
float(5) # 5.0
# Will raise ValueError if the string isn't a valid number:
int("hello") # โ ValueError!
Operators
# Arithmetic
10 + 3 # 13
10 - 3 # 7
10 * 3 # 30
10 / 3 # 3.3333... (always returns float)
10 // 3 # 3 (integer division โ drop the remainder)
10 % 3 # 1 (modulo โ remainder only)
2 ** 8 # 256 (2 to the power of 8)
# Comparison โ always returns True or False
5 == 5 # True
5 != 3 # True
5 > 3 # True
5 < 3 # False
5 >= 5 # True
# Logical
True and False # False (both must be True)
True or False # True (at least one must be True)
not True # False
# Assignment shortcuts
x = 10
x += 5 # x is now 15
x -= 3 # x is now 12
x *= 2 # x is now 24
x //= 4 # x is now 6
The 10 string methods you’ll actually use
| Method | Example | Result |
|---|---|---|
| .upper() | “prod-server”.upper() | “PROD-SERVER” |
| .lower() | “ALERT”.lower() | “alert” |
| .strip() | ” admin “.strip() | “admin” |
| .lstrip() / .rstrip() | ” admin “.lstrip() | “admin ” (left only) |
| .replace(old, new) | “prod-db”.replace(“prod”, “dev”) | “dev-db” |
| .split(sep) | “a,b,c”.split(“,”) | [“a”, “b”, “c”] |
| .join(list) | “-“.join([“a”,”b”,”c”]) | “a-b-c” |
| .startswith(s) | “error: timeout”.startswith(“error”) | True |
| .endswith(s) | “report.csv”.endswith(“.csv”) | True |
| .find(s) | “prod-db-01”.find(“db”) | 5 (index position) |
f-Strings
# Basic f-string โ put variables in {}
name = "Priya"
role = "DBA"
print(f"Welcome, {name}. Your role is {role}.")
# Welcome, Priya. Your role is DBA.
# Expressions inside {}
tickets_open = 12
tickets_closed = 38
print(f"Total tickets: {tickets_open + tickets_closed}")
# Total tickets: 50
# Format numbers โ 2 decimal places
cpu = 73.456789
print(f"CPU Usage: {cpu:.2f}%")
# CPU Usage: 73.46%
# Pad text for aligned columns
print(f"{'Server':20} {'Status':10} {'CPU':>6}")
print(f"{'prod-db-01':20} {'Online':10} {73.4:>6.1f}%")
print(f"{'dev-api-02':20} {'Offline':10} {0.0:>6.1f}%")
# Server Status CPU
# prod-db-01 Online 73.4%
# dev-api-02 Offline 0.0%
These examples are deliberately practical. Each one uses only what you’ve learned in M1 โ variables, types, operators, string methods, and f-strings. No loops, no functions, no imports yet. Just the fundamentals doing real work.
Calculates ticket resolution stats for a shift and formats them into a printable summary. This is the kind of quick report a helpdesk lead might generate at the end of a day.
# IT Support: Daily ticket summary
analyst_name = "Kiran Mehta"
shift = "Morning Shift (08:00 โ 16:00)"
tickets_open = 14
tickets_closed = 31
avg_resolution_mins = 22.7
total = tickets_open + tickets_closed
close_rate = (tickets_closed / total) * 100
print("=" * 42)
print(f" TICKET SUMMARY โ {shift}")
print("=" * 42)
print(f" Analyst : {analyst_name}")
print(f" Total tickets : {total}")
print(f" Closed : {tickets_closed}")
print(f" Still open : {tickets_open}")
print(f" Close rate : {close_rate:.1f}%")
print(f" Avg resolution : {avg_resolution_mins} mins")
print("=" * 42)
TICKET SUMMARY โ Morning Shift (08:00 โ 16:00)
==========================================
Analyst : Kiran Mehta
Total tickets : 45
Closed : 31
Still open : 14
Close rate : 68.9%
Avg resolution : 22.7 mins
==========================================
Builds an Oracle database connection string from individual components and validates that the port is a number. A DBA or Python script connecting to a database will do something like this before opening any connection.
# Database: Build and display a connection string
db_host = " ora-prod-01.internal " # note the extra spaces
db_port_str = "1521"
db_service = "ORCL"
db_user = "APP_USER"
# Clean the host name (strip whitespace, force lowercase)
db_host_clean = db_host.strip().lower()
# Convert port to integer for validation
db_port = int(db_port_str)
port_valid = db_port > 0 and db_port <= 65535
# Build the connection string (Oracle JDBC style)
conn_str = f"jdbc:oracle:thin:@{db_host_clean}:{db_port}/{db_service}"
print(f"Host (raw) : '{db_host}'")
print(f"Host (clean) : '{db_host_clean}'")
print(f"Port valid? : {port_valid}")
print(f"User : {db_user}")
print(f"Connection : {conn_str}")
Host (clean) : ‘ora-prod-01.internal’
Port valid? : True
User : APP_USER
Connection : jdbc:oracle:thin:@ora-prod-01.internal:1521/ORCL
Parses a single server log line using string methods โ extracts the timestamp, severity level, and message. DevOps engineers do this kind of parsing constantly when building log monitors or alert scripts.
# DevOps: Parse a log line using string methods
log_line = "2026-06-14 09:33:12 [ERROR] Disk usage at 94% on /dev/sda1"
# Extract timestamp โ first 19 characters
timestamp = log_line[:19]
# Extract severity level โ it's inside the square brackets
bracket_start = log_line.find("[") + 1
bracket_end = log_line.find("]")
severity = log_line[bracket_start:bracket_end]
# Extract message โ everything after the closing bracket + space
message = log_line[bracket_end + 2:]
# Check if this is an alert-worthy entry
is_error = severity == "ERROR"
is_warning = severity == "WARNING"
needs_alert = is_error or is_warning
print(f"Timestamp : {timestamp}")
print(f"Severity : {severity}")
print(f"Message : {message}")
print(f"Alert needed: {needs_alert}")
Severity : ERROR
Message : Disk usage at 94% on /dev/sda1
Alert needed: True
Calculates basic statistics from a small data sample using Python’s built-in functions and arithmetic operators โ without importing any library. A quick sanity check you’d run before feeding data into a model.
# AI/ML: Quick stats on a response-time dataset (no libraries needed)
# Sample inference times in milliseconds (7 API calls)
t1, t2, t3, t4, t5, t6, t7 = 312, 287, 445, 298, 501, 316, 274
total_ms = t1 + t2 + t3 + t4 + t5 + t6 + t7
count = 7
average_ms = total_ms / count
min_ms = min(t1, t2, t3, t4, t5, t6, t7)
max_ms = max(t1, t2, t3, t4, t5, t6, t7)
range_ms = max_ms - min_ms
# SLA check: flag if average exceeds 400ms
sla_target = 400
sla_breached = average_ms > sla_target
print("=== Inference Latency Report ===")
print(f"Samples : {count}")
print(f"Total : {total_ms} ms")
print(f"Average : {average_ms:.1f} ms")
print(f"Min / Max : {min_ms} ms / {max_ms} ms")
print(f"Range : {range_ms} ms")
print(f"SLA breach : {sla_breached}")
Samples : 7
Total : 2433 ms
Average : 347.6 ms
Min / Max : 274 ms / 501 ms
Range : 227 ms
SLA breach : False
Takes a raw report name and formats it into a standardised, safe file name โ lowercase, spaces replaced by underscores, date appended. Every automation script that saves files needs something like this.
import datetime
# Automation: Standardise a file name before saving
raw_name = " Monthly Sales REPORT โ June 2026 "
report_date = datetime.date.today()
file_ext = "csv"
# Step 1: strip whitespace
clean = raw_name.strip()
# Step 2: lowercase everything
clean = clean.lower()
# Step 3: replace spaces and dashes with underscores
clean = clean.replace(" ", "_")
clean = clean.replace("โ", "_")
clean = clean.replace("-", "_")
# Step 4: remove any double underscores that crept in
while "__" in clean:
clean = clean.replace("__", "_")
# Step 5: append date and extension
date_str = str(report_date).replace("-", "") # "20260614"
file_name = f"{clean}_{date_str}.{file_ext}"
print(f"Raw input : '{raw_name}'")
print(f"File name : '{file_name}'")
print(f"Length : {len(file_name)} characters")
File name : ‘monthly_sales_report_june_2026_20260614.csv’
Length : 43 characters
Write each exercise as a separate .py file and run it. These are designed to take 5โ10 minutes each. The goal isn’t to memorise syntax โ it’s to get comfortable with the idea of writing variables, doing something with them, and printing the result.
[WARNING] auth-service โ Login failed: user not found (HTTP 401)
๐ Employee Onboarding Welcome Script
Your IT team onboards new employees every Monday. Currently someone manually drafts the welcome message. Your task: build a Python script called onboarding.py that generates the complete onboarding summary automatically from stored variables.
- Store the following as variables: employee full name, employee ID (integer), job title, department, assigned laptop model, assigned email address (raw, with extra spaces and mixed case), temporary password, and start date as a string.
- Clean the email address using string methods: strip whitespace and convert to lowercase.
- Calculate the employee ID formatted with leading zeros to always be 6 digits โ e.g. ID 1042 becomes “001042”. Use an f-string format specifier: f”{emp_id:06d}”.
- Check whether the assigned email ends with your company’s domain (e.g. @yourcompany.com) and store the result as a boolean called email_valid.
- Print a clean, formatted onboarding welcome card that shows all the above information. Include a section header, the employee details, their system access credentials, and an email_valid confirmation line at the bottom.
These questions test whether you understood the concepts, not just whether you can copy syntax. Read each one carefully. Aim for 4/5 before moving to M2.
port = "5432" and then try result = port + 1. What happens?= and == in Python?"error: timeout".startswith("error") return?cpu = 87.6789 rounded to one decimal place inside a sentence. Which f-string does this correctly?17 % 5 evaluate to, and why would this operator be useful in a real script?