### Overview and What You Will Learn * What Python is and where it is used in the real world * Why Python is considered one of the most beginner-friendly languages * How Python compares to Bash and why ops engineers use both * How to install Python and check your version * How to use the Python interactive shell * How to write and run your first Python script file ### Why This Matters Python is the most popular programming language in the world right now. It runs Netflix recommendation engines, Instagram's backend, NASA's data pipelines, and the automation scripts that keep millions of servers healthy. If you are getting into DevOps, cloud engineering, data work, or AI operations, Python is not optional - it is the language the entire ecosystem is built on. The good news is that Python was designed to be readable. It looks almost like plain English, and you can build genuinely useful things within your first week of learning it. ### What Python Is Python is a general-purpose programming language - it can be used for almost anything. Web development, data analysis, machine learning, automation, scripting, building tools, writing games. Unlike specialised languages that are good at one thing, Python is the Swiss Army knife of programming. It was created by Guido van Rossum and first released in 1991. The name comes from Monty Python's Flying Circus, the British comedy group - not the snake. Though the snake logo stuck. What makes Python different from many languages: * It reads almost like English. `if age > 18:` means exactly what it says. * You do not declare variable types. Python figures them out automatically. * There are no curly braces or semicolons to worry about. Indentation structures the code. * The standard library is enormous. Most things you want to do already have a built-in solution. ### Where Python Is Used Python is everywhere once you start looking: * Web development - Django and Flask power millions of websites * Data science and machine learning - NumPy, Pandas, TensorFlow, PyTorch are all Python * DevOps and automation - Ansible, Airflow, and most CI/CD tooling is Python * Cloud infrastructure - AWS Boto3, Google Cloud SDK, Azure SDK are Python-first * AIOps and SRE - anomaly detection models, alert routing, log analysis pipelines * Scripting - replacing long Bash scripts with readable, maintainable Python code ### Python vs Bash - A Quick Comparison If you work on Linux servers, you already know Bash. A common question is whether to write something in Bash or Python. Both are useful and knowing when to reach for each is a real skill. Bash is better when you are gluing existing command-line tools together - copy files, restart a service, check if a process is running, pipe one command into another. Python is better when you need to work with data, handle errors properly, call APIs, build something other people will maintain, or do anything that would turn your Bash script into an unreadable tangle of pipes and dollar signs. | Scenario | Use | | :--- | :--- | | Restart nginx if it is down | Bash | | Parse a JSON API response | Python | | Copy files to an archive folder | Bash | | Read a CSV and find anomalies | Python | | Chain three CLI tools together | Bash | | Send a formatted Slack alert | Python | ### Installing Python Python 3 is what you want. Python 2 is obsolete and was retired in 2020. ```bash ## Check if Python is already installed python3 --version ## Expected: Python 3.10.x or higher ## Install on Ubuntu or Debian sudo apt update sudo apt install python3 python3-pip ## Install on macOS using Homebrew brew install python3 ## Windows: download the installer from python.org ## Make sure to check "Add Python to PATH" during installation ``` ### The Python Interactive Shell The interactive shell lets you type Python and see results immediately. Start it with `python3` and you get a `>>>` prompt. ```bash python3 ``` ```python >>> 2 + 2 4 >>> "hello" + " world" 'hello world' >>> print("My first Python line") My first Python line >>> exit() ``` Think of it as a calculator that understands Python. Great for testing small ideas. ### Your First Python Script File A script is a text file with a `.py` extension. You write code in it and run the whole file at once. ```python ## hello.py print("Hello, world!") print("My name is Priya") print("I am learning Python") ``` ```bash python3 hello.py ``` ```text Hello, world! My name is Priya I am learning Python ``` That is it. Every Python program you will ever write follows this same pattern. > 💡 **Tip:** `print()` is how Python displays output. Everything inside the parentheses gets printed to the screen. You will use it constantly while learning to check what your code is doing. ---
### Overview and What You Will Learn * What a variable is and how to create one * The four core data types - strings, integers, floats, and booleans * How Python determines types automatically * How to check the type of any variable * How to convert between types ### Why This Matters Every useful program stores information. A username, a number, a yes or no answer, a list of items. Variables are how you store and label that information so you can use it later. Understanding data types means understanding what kind of information you are working with at any moment - which determines what you can do with it. ### What is a Variable A variable is a name that points to a value stored in memory. Think of it like a labeled box. You put something in the box, give it a label, and refer to it by that label whenever you need it. ```python name = "Priya" age = 24 temperature = 36.6 is_raining = False ``` The `=` sign is the assignment operator - it puts the value on the right into the variable on the left. Rules for naming variables: * Start with a letter or underscore, never a number * Use letters, numbers, and underscores only - no spaces * Case sensitive: `name`, `Name`, and `NAME` are three different variables * Cannot use Python keywords like `if`, `for`, `while`, `True`, `False` * Good names are descriptive: `user_age` is better than `x` ### Strings - Text Data A string is any sequence of characters. You create one by wrapping text in quotes. ```python ## Single quotes and double quotes both work first_name = 'Rahul' last_name = "Sharma" ## For text containing an apostrophe, use double quotes message = "It's a great day to learn Python" ## For multiple lines, use triple quotes paragraph = """This is line one. This is line two. This is line three.""" ``` ### Numbers - Integers and Floats An integer is a whole number with no decimal point. ```python age = 25 year = 2026 temperature = -3 ``` A float is a number with a decimal point. ```python price = 499.99 pi = 3.14159 cpu_usage = 87.4 ``` Basic math works exactly as you expect: ```python a = 10 b = 3 print(a + b) ## 13 print(a - b) ## 7 print(a * b) ## 30 print(a / b) ## 3.3333 - division always returns float print(a // b) ## 3 - floor division, drops the decimal print(a % b) ## 1 - modulo, remainder after division print(a ** b) ## 1000 - exponentiation, 10 to the power of 3 ``` ### Booleans - True or False A boolean holds exactly one of two values: `True` or `False`. The capital first letter matters. ```python is_logged_in = True has_permission = False is_weekend = True ``` Booleans power every decision in your program. Every `if` statement ultimately checks a boolean. ### Python Determines Types Automatically Python figures out the type from what you assign. This is called dynamic typing. ```python x = "hello" ## x is a string x = 42 ## now x is an integer x = 3.14 ## now x is a float x = True ## now x is a boolean ``` ### Checking and Converting Types ```python name = "Priya" age = 24 height = 5.6 print(type(name)) ## <class 'str'> print(type(age)) ## <class 'int'> print(type(height)) ## <class 'float'> ``` ```python ## String to number age_text = "25" age_number = int(age_text) print(age_number + 1) ## 26 price_text = "499.99" price_float = float(price_text) print(price_float * 2) ## 999.98 ## Number to string score = 95 result = "Your score is " + str(score) print(result) ## Your score is 95 ## int() truncates floats, it does NOT round print(int(3.9)) ## 3, not 4 print(int(-2.7)) ## -2, not -3 ``` > 🔴 **Common Mistake:** Trying to add a string and a number directly. `"Score: " + 95` crashes with a TypeError. Always convert the number to a string first: `"Score: " + str(95)`. ---
### Overview and What You Will Learn * How to create strings with different quote styles * How indexing works - accessing individual characters * How slicing works - getting a portion of a string * The most useful string methods * How to format strings with f-strings * How to check if a string contains something ### Why This Matters Strings are everywhere. User input is a string. Log file lines are strings. File paths are strings. API responses contain strings. Being comfortable with string operations means you can process text data confidently. ### String Indexing Every character in a string has a position called an index. Python counts from zero. ```python name = "Python" ## P y t h o n ## 0 1 2 3 4 5 <- positive indices ## -6 -5 -4 -3 -2 -1 <- negative indices (count from end) print(name[0]) ## P print(name[1]) ## y print(name[-1]) ## n - last character print(name[-2]) ## o - second to last ``` ### String Slicing Slicing extracts a substring. The syntax is `string[start:end]` where start is inclusive and end is exclusive. ```python language = "Python is great" print(language[0:6]) ## Python print(language[7:9]) ## is print(language[10:]) ## great - from position 10 to end print(language[:6]) ## Python - from start to position 5 print(language[-5:]) ## great - last 5 characters print(language[::-1]) ## taerg si nohtyP - reversed ``` ### Common String Methods ```python message = " Hello, World! " ## Case print(message.upper()) ## " HELLO, WORLD! " print(message.lower()) ## " hello, world! " print("hello world".title()) ## "Hello World" ## Whitespace print(message.strip()) ## "Hello, World!" - removes both ends print(message.lstrip()) ## "Hello, World! " - left only print(message.rstrip()) ## " Hello, World!" - right only ## Finding and replacing sentence = "The cat sat on the mat" print(sentence.replace("cat", "dog")) ## "The dog sat on the mat" print(sentence.count("at")) ## 3 print(sentence.find("sat")) ## 8 - index of first occurrence print(sentence.find("xyz")) ## -1 - not found ## Splitting and joining csv_line = "Rahul,25,Mumbai,Engineer" parts = csv_line.split(",") print(parts) ## ['Rahul', '25', 'Mumbai', 'Engineer'] print(parts[0]) ## Rahul words = ["Python", "is", "fun"] result = " ".join(words) print(result) ## Python is fun ## Checking content email = "rahul@devops.in" print(email.startswith("rahul")) ## True print(email.endswith(".com")) ## False print("@" in email) ## True print("12345".isdigit()) ## True print(len("Python")) ## 6 ``` ### f-Strings - The Best Way to Format Output Put `f` before the opening quote and wrap variables in curly braces. ```python name = "Priya" age = 24 score = 94.7 print(f"Name: {name}, Age: {age}") print(f"Score: {score:.1f}%") ## .1f = 1 decimal place print(f"Next year you will be {age + 1}") print(f"Uppercase: {'hello'.upper()}") ## methods work inside {} ``` f-strings are the standard in modern Python. They are cleaner and faster than older formatting methods. ---
### Overview and What You Will Learn * What a list is and when to use one * Creating a list and accessing items by index * Adding and removing items * Looping through a list * Slicing a list * Sorting and reversing * Useful list methods ### Why This Matters Lists are one of the most important data structures in Python. Any time you have a collection of things - a group of names, a series of temperatures, a batch of log lines - you store them in a list. Almost every real Python program uses lists constantly. ### Creating and Accessing Lists ```python fruits = ["apple", "banana", "mango", "orange"] numbers = [1, 2, 3, 4, 5] mixed = ["hello", 42, True, 3.14] empty = [] print(fruits[0]) ## apple - first item print(fruits[1]) ## banana print(fruits[-1]) ## orange - last item print(fruits[-2]) ## mango - second to last print(len(fruits)) ## 4 ``` ### Adding Items ```python colors = ["red", "green", "blue"] colors.append("yellow") ## add to end print(colors) ## ['red', 'green', 'blue', 'yellow'] colors.insert(1, "purple") ## add at index 1 print(colors) ## ['red', 'purple', 'green', 'blue', 'yellow'] more_colors = ["pink", "white"] colors.extend(more_colors) ## add all items from another list ``` ### Removing Items ```python animals = ["cat", "dog", "bird", "fish", "dog"] animals.remove("dog") ## removes first occurrence print(animals) ## ['cat', 'bird', 'fish', 'dog'] last = animals.pop() ## removes and returns last item print(last) ## dog first = animals.pop(0) ## removes and returns item at index 0 print(first) ## cat numbers = [10, 20, 30, 40] del numbers[1] print(numbers) ## [10, 30, 40] numbers.clear() ## removes everything ``` ### Looping Through a List ```python cities = ["Mumbai", "Pune", "Hyderabad", "Chennai", "Bengaluru"] ## Simple loop for city in cities: print(city) ## Loop with index for index, city in enumerate(cities): print(f"{index + 1}. {city}") ## 1. Mumbai ## 2. Pune ## 3. Hyderabad ... ``` ### List Slicing ```python numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(numbers[2:5]) ## [2, 3, 4] print(numbers[:4]) ## [0, 1, 2, 3] print(numbers[6:]) ## [6, 7, 8, 9] print(numbers[::2]) ## [0, 2, 4, 6, 8] - every second item print(numbers[::-1]) ## [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] - reversed ``` ### Sorting and Useful Functions ```python scores = [87, 42, 95, 13, 67] scores.sort() ## modifies list in place print(scores) ## [13, 42, 67, 87, 95] scores.sort(reverse=True) print(scores) ## [95, 87, 67, 42, 13] ## sorted() returns a new list, original is unchanged names = ["Zeynep", "Ananya", "Riya", "Mohan"] sorted_names = sorted(names) print(sorted_names) ## ['Ananya', 'Mohan', 'Riya', 'Zeynep'] print(names) ## unchanged numbers = [3, 1, 4, 1, 5, 9, 2, 6] print(min(numbers)) ## 1 print(max(numbers)) ## 9 print(sum(numbers)) ## 31 print(3 in numbers) ## True ``` ---
### Overview and What You Will Learn * What a dictionary is and when to use it * Creating a dictionary and accessing values by key * Adding, updating, and deleting keys * Looping through keys, values, and both * Nested dictionaries * Safe key access with .get() ### Why This Matters Dictionaries store data as key-value pairs. Almost every API response you will ever receive is a dictionary. Config files become dictionaries when you read them. Understanding dictionaries makes working with real-world data feel natural. ### Creating and Accessing ```python person = { "name": "Ananya", "age": 27, "city": "Bengaluru", "active": True } print(person["name"]) ## Ananya print(person["age"]) ## 27 ``` ### Adding, Updating, Deleting ```python student = {"name": "Rohan", "grade": "A", "score": 92} student["subject"] = "Mathematics" ## add new key student["score"] = 95 ## update existing value del student["grade"] ## delete a key score = student.pop("score") ## delete and return value print(score) ## 95 ``` ### Looping ```python config = {"host": "localhost", "port": 5432, "timeout": 30} for key in config: ## keys only print(key) for value in config.values(): ## values only print(value) for key, value in config.items(): ## both together print(f"{key}: {value}") ``` ### Safe Key Access with .get() Direct access crashes if the key does not exist. `.get()` returns `None` safely. ```python user = {"name": "Kavya", "email": "kavya@example.com"} print(user["name"]) ## Kavya - works ## print(user["phone"]) ## KeyError - crashes print(user.get("phone")) ## None - safe print(user.get("phone", "not provided")) ## not provided - custom default ``` > 📌 **Remember:** Use `.get()` whenever a key might not be present. This is especially important when parsing API responses where you cannot guarantee every field exists. ### Nested Dictionaries ```python employee = { "name": "Mohan", "address": { "city": "Pune", "pincode": "411001" }, "skills": ["Python", "Linux", "Docker"] } print(employee["name"]) ## Mohan print(employee["address"]["city"]) ## Pune print(employee["skills"][0]) ## Python ## Safe nested access city = employee.get("address", {}).get("city", "unknown") ``` ---
### Overview and What You Will Learn * What makes a tuple different from a list * When and why to use tuples * What a set is and what makes it special * Common set operations * Real use cases for each ### Tuples - Immutable Sequences A tuple is like a list but you cannot change it after creating it. Created with parentheses. ```python coordinates = (19.0760, 72.8777) rgb_red = (255, 0, 0) days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") print(coordinates[0]) ## 19.076 print(days[-1]) ## Friday print(len(days)) ## 5 ## Cannot modify ## days[0] = "Sunday" ## TypeError ## Tuple unpacking x, y = coordinates print(x) ## 19.076 print(y) ## 72.8777 ## Functions returning multiple values use tuples def min_max(numbers): return min(numbers), max(numbers) low, high = min_max([3, 1, 7, 2, 9]) print(low, high) ## 1 9 ``` Use tuples when data should not change - coordinates, RGB colors, fixed config values. They also allow a collection to be used as a dictionary key, which lists cannot. ### Sets - Collections of Unique Items A set stores unordered unique values. Duplicates are removed automatically. ```python fruits = {"apple", "banana", "mango", "apple", "banana"} print(fruits) ## {'mango', 'banana', 'apple'} - duplicates gone print("apple" in fruits) ## True - very fast membership check print("grape" in fruits) ## False fruits.add("orange") fruits.remove("banana") ## raises KeyError if not present fruits.discard("xyz") ## safe - no error if not present ``` ```python ## Set operations set_a = {1, 2, 3, 4, 5} set_b = {4, 5, 6, 7, 8} print(set_a | set_b) ## {1, 2, 3, 4, 5, 6, 7, 8} - union print(set_a & set_b) ## {4, 5} - intersection (in both) print(set_a - set_b) ## {1, 2, 3} - difference (in a but not b) ``` ```python ## Practical use - remove duplicates from a list items = ["nginx", "app", "nginx", "db", "app", "nginx"] unique = list(set(items)) print(unique) ## unique items only ``` ---
Overview and What You Will Learn What Python is and where it is used in the real world Why Python is considered one of t...
Overview and What You Will Learn What a variable is and how to create one The four core data types - strings, integers, ...
Overview and What You Will Learn How to create strings with different quote styles How indexing works - accessing indivi...
Overview and What You Will Learn What a list is and when to use one Creating a list and accessing items by index Adding ...
Overview and What You Will Learn What a dictionary is and when to use it Creating a dictionary and accessing values by k...
Overview and What You Will Learn What makes a tuple different from a list When and why to use tuples What a set is and w...
Overview and What You Will Learn How if, elif, and else work Comparison operators Logical operators - and, or, not Neste...
Overview and What You Will Learn How for loops work and when to use them How while loops work and when to use them break...
Overview and What You Will Learn What a function is and why to write one Defining and calling functions Parameters and a...
Overview and What You Will Learn What a module is and how to import one Different import styles Useful built-in modules ...
Overview and What You Will Learn How to open, read, and write files Reading line by line for large files Working with CS...
Overview and What You Will Learn What exceptions are and why they happen try, except, else, finally Catching specific ex...
Overview and What You Will Learn List comprehensions - the Pythonic shortcut Dictionary comprehensions Useful built-ins ...
Overview and What You Will Learn What regular expressions are and when to use them The re module - search, findall, sub ...
Overview and What You Will Learn What an API is and how HTTP works GET and POST requests with the requests library Readi...
Overview Three complete working programs that combine everything you have learned. Type each one yourself - do not copy ...
Python Cheat Sheet Variables and Types Strings Lists Dictionaries Conditionals Loops Functions Files Error Handling Comm...
Aligns directly with DevOps, Site Reliability (SRE), and Platform Engineering job descriptions.