Featured image

Table of Contents Link to heading

Introduction Link to heading

Python is one of the most widely used programming languages today, known for its simplicity and powerful capabilities. It allows developers to write clean and expressive code with ease, even though it may trade speed for flexibility. Python is distributed open-source, meaning anyone can download and use it freely. The primary hub for Python resources is python.org.

Key Features of Python Link to heading

  • Cross-platform: Code runs on Windows, Mac, and Linux without modifications.
  • Garbage collection: Python automatically manages memory allocation and cleanup.
  • Dynamic typing: You don’t need to declare variable types explicitly.
  • Rich standard library: Python includes built-in modules for everything from networking to data manipulation.

Variables in Python Link to heading

In Python, variables act as named containers that hold references to values. Unlike in some languages, Python does not require pre-declaration.

name = "Alice"
age = 25
age = 30  # Now 'age' refers to a new integer

Memory Management Link to heading

Python handles garbage collection, automatically discarding unused values.

msg = "Hello"
greeting = msg + "!"
greeting = "Hi"

The "Hello!" string is left as garbage.

Numbers in Python Link to heading

Python supports two primary numerical types:

  • Integers (int): Whole numbers, e.g., 42, -7.
  • Floating-point (float): Decimal numbers, e.g., 3.14, -2.5.

Integer Operations Link to heading

x = 10 // 3  # Integer division (rounded down)
y = 5 % 2    # Modulus (remainder)
z = 2 ** 4   # Exponentiation

Floating-point Precision Link to heading

Due to binary representation, floating-point numbers may introduce small rounding errors.

print(0.1 + 0.2)  # Output: 0.30000000000000004

Conditional Statements Link to heading

Python uses if, elif, and else to control program flow.

temperature = 30
if temperature > 35:
    print("Too hot!")
elif temperature < 15:
    print("Too cold!")
else:
    print("Just right!")

Boolean Logic Link to heading

Boolean operators simplify decision-making:

  • and: Both conditions must be True
  • or: At least one condition must be True
  • not: Reverses True or False
logged_in = True
admin = False

if logged_in and not admin:
    print("Regular user access granted")

Strings in Python Link to heading

Strings represent sequences of characters.

phrase = "Python Programming"
print(phrase[0])  # First character
print(phrase[-1]) # Last character

Common String Methods Link to heading

text = "  Learn Python!  "
print(text.strip())        # Removes leading/trailing spaces
print(text.lower())        # Converts to lowercase
print(text.replace("Learn", "Master"))  # Replace words

Lists in Python Link to heading

Lists store multiple ordered values.

colors = ["red", "green", "blue"]
colors.append("yellow")  # Adds an item
print(colors)

Dictionaries in Python Link to heading

Dictionaries store key-value pairs.

user = {"name": "Alice", "age": 25}
print(user["name"])  # Output: Alice

Use .get() to avoid errors:

print(user.get("email", "Not provided"))

Loops in Python Link to heading

For Loop Link to heading

for num in range(1, 4):
    print(num)  # Outputs 1, 2, 3

While Loop Link to heading

count = 0
while count < 5:
    print("Looping:", count)
    count += 1

Functions in Python Link to heading

Functions encapsulate reusable logic.

def greet(name):
    return f"Hello, {name}!"

print(greet("Bob"))

Modules in Python Link to heading

Python supports importing modules for extra functionality.

import math
print(math.sqrt(16))  # Output: 4.0

File Handling Link to heading

Reading and writing files in Python:

with open("data.txt", "r") as file:
    content = file.read()
    print(content)

Sorting Data Link to heading

Sorting lists and custom objects:

numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # Output: [1, 1, 3, 4, 5]

For custom sorting, use a key function:

students = [("Alice", 85), ("Bob", 72), ("Charlie", 91)]
students.sort(key=lambda x: x[1])  # Sort by scores
print(students)

File Handling in Python Link to heading

Python makes reading and writing files simple using the open() function.

Reading a File Link to heading

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
  • The with statement ensures the file is automatically closed after reading.
  • "r" mode opens the file for reading.

Writing to a File Link to heading

with open("output.txt", "w") as file:
    file.write("Hello, Python!")
  • "w" mode overwrites the file if it exists.
  • Use "a" mode to append instead of overwriting.

Reading Line by Line Link to heading

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # Removes extra spaces/newlines

Python Coding Style (PEP 8) Link to heading

PEP 8 is the official style guide for Python, ensuring readability and consistency.

Indentation Link to heading

  • Use 4 spaces per indentation level.
  • Avoid tabs for indentation.
def example_function():
    print("Indented correctly")

Maximum Line Length Link to heading

  • Keep lines under 79 characters.
  • Use parentheses for line continuation.
long_variable_name = (
    "This is a long string that is split across multiple lines "
    "to maintain readability."
)

Naming Conventions Link to heading

  • Variables & functions: Use snake_case
  • Classes: Use CamelCase
  • Constants: Use UPPER_CASE
class MyClass:
    MAX_LIMIT = 100

def calculate_total(price, quantity):
    return price * quantity

Whitespace Best Practices Link to heading

  • Avoid extra spaces inside parentheses or brackets.
  • Use spaces around operators.
# ✅ Correct
result = (x + y) * z

# ❌ Incorrect
result = ( x+y )*z

Commenting Guidelines Link to heading

  • Use docstrings for functions.
  • Write clear and concise comments.
def add_numbers(a, b):
    """Returns the sum of two numbers."""
    return a + b

Conclusion Link to heading

Python is a powerful and flexible language suitable for many applications, including web development, data science, and automation. Its readability and intuitive syntax make it a favourite among beginners and experts alike.