Python
Comprehensive Python notes for DevOps engineers — syntax, data types, control flow, functions, and practical examples.
Introduction to Python: Comprehensive Notes
1. Introduction to Python
- Invented By: Python was created by Guido van Rossum.
- Year: Python was first released in 1991.
- Usage: Python is widely used in web development, data science, artificial intelligence, automation, and more.
- Why Python?
- Readability: Simple and clean syntax.
- Community Support: Extensive libraries and frameworks.
- Versatility: Used in various domains like web development, data science, etc.
2. Python Syntax
- Indentation: Python uses indentation (spaces or tabs) to define blocks of code.
- Example:
if True:
print("This is indented")- Comments:
Single-line: Use # for single-line comments.
Multi-line: Use triple quotes (''' or """) for multi-line comments. - Example:
# This is a single-line comment
"""
This is a
multi-line comment
"""3. Data Types
- Numeric Types: int, float, complex
- Sequence Types: str, list, tuple
- Mapping Type: dict
- Set Types: set, frozenset
- Boolean Type: bool
- None Type: NoneType
- Example:
a = 10 # int
b = 3.14 # float
c = 'Hello' # str
d = True # bool4. Variables
- Declaration: Variables are created when you assign a value to them.
- Dynamic Typing: Python variables do not require an explicit declaration of type.
- Example:
x = 5 # Integer
y = "Hello" # String
z = 3.14 # Float5. Operators
- Arithmetic Operators: +, -, *, /, //, %, **
- Comparison Operators: ==, !=, >, <, >=, <=
- Logical Operators: and, or, not
- Membership Operators: in, not in
- Identity Operators: is, is not
- Example:
a = 10
b = 20
print(a == b) # False
print(a is b) # False6. Control Flow and Looping Statements
- Conditional Statements:
- if, elif, else
- Example:
x = 10
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")- Looping Statements:
- For Loop:
for i in range(5):
print(i)- While Loop:
i = 0
while i < 5:
print(i)
i += 1- Loop Control: break, continue, pass
7. Functions
- Introduction: Functions allow for code reuse and modularity.
- Syntax:
def function_name(parameters):
"""Docstring"""
statement(s)Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))- Arguments: Positional, keyword, default values.
- Return Statement: Used to return values from a function
8. Modules and Packages
- Modules: A Python file containing definitions and statements.
- Importing Modules:
import math
print(math.sqrt(16))- Packages: A collection of modules in directories that include a special __init__.py file.
- Creating a Module: Any .py file can be used as a module.
- Example:
from math import pi
print(pi)9. File Handling
- Reading and Writing Files:
- Open a file: open(filename, mode)
- Modes: r (read), w (write), a (append), b (binary mode)
- Example:
with open('file.txt', 'r') as file:
content = file.read()
print(content)- Writing to a File:
with open('file.txt', 'w') as file:
file.write("Hello, World!")10. Error Handling
- Try-Except Block:
try:
# Code that may throw an error
x = 1 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
finally:
print("This runs no matter what.")- Multiple Exceptions: Handle multiple exceptions using tuples.
11. Object-Oriented Programming (OOP)
- Class and Objects:
- Class Definition:
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}"- Object Creation:
obj = MyClass("Alice")
print(obj.greet())- Inheritance: Allows one class to inherit attributes and methods from another.
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
dog = Dog()
print(dog.sound()) # Output: Bark- Polymorphism: Same method name, different implementations.
12. List Comprehensions
- Syntax: [expression for item in iterable if condition]
- Example:
squares = [x**2 for x in range(10)]
print(squares)- Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
13. Lambda Functions
- Anonymous Functions: Created using the lambda keyword.
- Syntax: lambda arguments: expression
- Example:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 514. Map, Filter, and Reduce
- Map: Applies a function to all items in an iterable.
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # Output: [1, 4, 9, 16]- Filter: Filters items based on a condition.
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4]- Reduce: Reduces a sequence to a single value.
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 2415. Common Built-in Functions
- Examples: len(), sum(), max(), min(), sorted(), type(), range()
- Example Usage:
numbers = [1, 2, 3, 4]
print(len(numbers)) # Output: 4
print(sum(numbers)) # Output: 1016. Debugging
- Simple Debugging: Use print() statements to track variables.
- Python Debugger (pdb):
import pdb
pdb.set_trace()- Setting Breakpoints: Can be used to pause execution and inspect code.
This comprehensive document covers the fundamental concepts of Python and provides clear examples for each topic.
Comments
Questions, corrections, war stories — all welcome. Sign in with GitHub to join the discussion.