Module 1: Python Fundamentals

M1: Python Fundamentals โ€” Python for Corporate Professionals | OTLMS
M1 ยท Python Fundamentals Python for Corporate Professionals

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.

6 topics ~60 min read Foundation level All roles
๐Ÿ“–
Concept โ€” The Building Blocks of Every Python Program
What variables, types, operators, and strings actually mean โ€” in plain English
โŒƒ
Topic 1

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.

Mental model: A variable is a labelled container. username = “Rahul” creates a container labelled username and puts the text “Rahul” inside it. Whenever you type username later in your code, Python opens that container and hands you “Rahul”.

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.

Topic 2

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

๐Ÿ’ก To check what type a variable is at any point, use the built-in type() function: type(cpu_usage) returns <class ‘float’>. This is genuinely useful when you’re debugging โ€” sometimes a number that looks like an integer is actually stored as a string, and that causes problems.
Topic 3

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.

โš ๏ธ A common error beginners hit: user input from input() is always a string, even if the user typed a number. So age = input(“Enter age: “) gives you “30”, not 30. You need age = int(input(“Enter age: “)) to get an integer.
Topic 4

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 -=, *=, /=.

One to watch: = is assignment (you’re storing a value). == is comparison (you’re asking whether two things are equal). Mixing these up is one of the most common beginner mistakes โ€” and Python will usually tell you with a SyntaxError.
Topic 5

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.

Topic 6

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.

๐Ÿ’ก f-strings also support expressions directly: f”CPU at {usage * 100:.1f}%” multiplies usage by 100 and formats it to one decimal place, all inside the string. You’ll use this pattern a lot in report generation.
โœ๏ธ
Syntax Reference
Every pattern from this module with annotated code and output
โŒƒ

Variables & assignment

Python
# 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

Python
# 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

Python
# 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

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

Python
# 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%
๐Ÿ’ก
Examples โ€” Fundamentals in Your Work Context
Five complete programs, one for each corporate role
โŒƒ

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.

Example 1 โ€” IT Support: Ticket summary report
IT Support

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.

Python
# 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)
Output
==========================================
  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
==========================================
Example 2 โ€” Database Developer: Connection string builder
Database Dev

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.

Python
# 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}")
Output
Host (raw) : ‘ ora-prod-01.internal ‘
Host (clean) : ‘ora-prod-01.internal’
Port valid? : True
User : APP_USER
Connection : jdbc:oracle:thin:@ora-prod-01.internal:1521/ORCL
Example 3 โ€” DevOps: Log line parser
DevOpsIT Support

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.

Python
# 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}")
Output
Timestamp : 2026-06-14 09:33:12
Severity : ERROR
Message : Disk usage at 94% on /dev/sda1
Alert needed: True
Example 4 โ€” AI / ML: Dataset quick stats
AI / ML

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.

Python
# 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}")
Output
=== Inference Latency Report ===
Samples : 7
Total : 2433 ms
Average : 347.6 ms
Min / Max : 274 ms / 501 ms
Range : 227 ms
SLA breach : False
Example 5 โ€” Automation: File name formatter
AutomationAll Roles

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.

Python
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")
Output
Raw input : ‘ Monthly Sales REPORT โ€” June 2026 ‘
File name : ‘monthly_sales_report_june_2026_20260614.csv’
Length : 43 characters
๐Ÿ‹๏ธ
Practice Exercises
Four tasks โ€” write the code yourself, then check the hint if you’re stuck
โŒƒ

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.

1
Server info card. Create variables for: a server name, its IP address, its OS type (as a string), its RAM in GB (integer), and whether it is currently online (boolean). Print all five using f-strings, formatted as a neat info card with labels aligned.
Use f-strings with padding to align the values. Something like f”{‘Server’:15}: {server_name}” โ€” the :15 pads the label to 15 characters so everything lines up. Run through each variable with its own print line.
2
Email address cleaner. Start with this messy string: ” PRIYA.SHARMA@Company.COM “. Write code that strips the whitespace and converts it to a clean, standardised lowercase email address. Then check whether it ends with “@company.com” and print whether the domain is valid.
Use .strip() first, then .lower(). For the domain check, use .endswith(“@company.com”) โ€” it returns True or False which you can store in a variable and print.
3
Storage calculator. You have three disk drives with the following sizes in GB: 500, 1024, and 2048. Calculate the total storage, the average size per drive, and what percentage of total storage the largest drive represents. Print all results with appropriate labels and 1 decimal place formatting.
Total: add the three values. Average: total divided by 3. Percentage: (largest / total) * 100. Use f”{value:.1f}” for 1 decimal place in your print statements.
4
Log line builder. You have the following separate variables: level = “WARNING”, service = “auth-service”, message = “Login failed: user not found”, and response_code = 401. Combine them into a single formatted log line that looks like this:
[WARNING] auth-service โ€” Login failed: user not found (HTTP 401)
Use an f-string to combine all four variables: f”[{level}] {service} โ€” {message} (HTTP {response_code})”. Notice that response_code is an integer, but inside an f-string Python converts it to a string automatically โ€” you don’t need str() here.
๐Ÿ“‹
Assignment โ€” M1
A real-world mini-program to complete independently โ€” estimated 30 minutes
โŒƒ

๐Ÿ“‹ 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.

  1. 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.
  2. Clean the email address using string methods: strip whitespace and convert to lowercase.
  3. 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}”.
  4. 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.
  5. 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.
โœ… Paste your script and its output in the comments below. If your output looks clean and all variables are used, you’re ready for M2 โ€” Control Flow.
๐Ÿง 
Quiz โ€” Check Your Understanding
5 questions ยท instant feedback ยท retake as many times as you need
โŒƒ

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.

1. You write port = "5432" and then try result = port + 1. What happens?
2. What is the difference between = and == in Python?
3. What does "error: timeout".startswith("error") return?
4. You want to print the value of cpu = 87.6789 rounded to one decimal place inside a sentence. Which f-string does this correctly?
5. What does 17 % 5 evaluate to, and why would this operator be useful in a real script?
Completed M1? Time to make your code think.
M2: Control Flow โ€” if/elif/else, for loops, while loops, break and continue.
Start M2 โ†’

Scroll to Top