What are all the basics of Python?
#python#basics#fundamentals#data-structures#oop#functions#async
Answer
Python Basics Overview
Python is a high-level, interpreted, dynamically typed language widely used in Gen AI engineering. Below are all the core concepts every Python developer must know.
1. Variables & Data Types
python# Numbers age = 25 # int price = 9.99 # float z = 3 + 4j # complex # String name = "Alice" multi = '''Multi line string''' # Boolean is_active = True is_done = False # None (null equivalent) result = None
| Type | Example | Notes |
|---|---|---|
text | text | Arbitrary precision |
text | text | 64-bit double |
text | text | Immutable, Unicode |
text | text text | Subclass of text |
text | text | Represents absence of value |
2. Control Flow
python# if / elif / else score = 85 if score >= 90: grade = "A" elif score >= 70: grade = "B" else: grade = "C" # Ternary expression label = "pass" if score >= 50 else "fail"
3. Loops
python# for loop for i in range(5): # 0, 1, 2, 3, 4 print(i) # while loop count = 0 while count < 3: count += 1 # Loop control for n in range(10): if n == 3: continue # skip 3 if n == 7: break # stop at 7 # List comprehension squares = [x**2 for x in range(6)] # [0, 1, 4, 9, 16, 25] evens = [x for x in range(10) if x % 2 == 0]
4. Data Structures
python# List — ordered, mutable fruits = ["apple", "banana", "cherry"] fruits.append("date") fruits[0] # "apple" fruits[1:3] # ["banana", "cherry"] # Tuple — ordered, immutable coords = (10, 20) x, y = coords # unpacking # Dictionary — key-value pairs person = {"name": "Alice", "age": 30} person["email"] = "alice@example.com" person.get("phone", "N/A") # safe access # Set — unordered, unique values tags = {"python", "ai", "ml", "python"} # {"python", "ai", "ml"} tags.add("nlp")
| Structure | Ordered | Mutable | Duplicates | Access |
|---|---|---|---|---|
text | Yes | Yes | Yes | By index |
text | Yes | No | Yes | By index |
text | Yes (3.7+) | Yes | Keys: No | By key |
text | No | Yes | No | No index |
5. Functions
python# Basic function def greet(name: str, greeting: str = "Hello") -> str: return f"{greeting}, {name}!" # *args and **kwargs def summarise(*args, **kwargs): print(args) # tuple of positional args print(kwargs) # dict of keyword args summarise(1, 2, 3, model="gpt-4", temp=0.7) # Lambda (anonymous function) double = lambda x: x * 2 # Higher-order functions nums = [3, 1, 4, 1, 5] print(sorted(nums)) # [1, 1, 3, 4, 5] print(list(map(double, nums))) # [6, 2, 8, 2, 10] print(list(filter(lambda x: x > 2, nums))) # [3, 4, 5]
6. Object-Oriented Programming (OOP)
pythonclass Animal: species = "Unknown" # class variable def __init__(self, name: str, sound: str): self.name = name # instance variable self.sound = sound def speak(self) -> str: return f"{self.name} says {self.sound}" def __repr__(self) -> str: return f"Animal(name={self.name!r})" class Dog(Animal): # inheritance def __init__(self, name: str): super().__init__(name, "Woof") def fetch(self, item: str) -> str: return f"{self.name} fetches the {item}" dog = Dog("Rex") print(dog.speak()) # Rex says Woof print(dog.fetch("ball")) # Rex fetches the ball
| OOP Concept | Python Mechanism |
|---|---|
| Encapsulation | text text |
| Inheritance | text |
| Polymorphism | Method overriding |
| Abstraction | text text |
7. Error Handling
pythontry: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") except (TypeError, ValueError) as e: print(f"Type/Value error: {e}") else: print("No error occurred") # runs only if no exception finally: print("Always runs") # cleanup code # Raise custom exception class ModelNotFoundError(Exception): pass def load_model(name: str): if name not in ["gpt-4", "llama"]: raise ModelNotFoundError(f"{name} is not available")
8. Modules & Packages
python# Standard library import os import sys from pathlib import Path from datetime import datetime, timedelta # Third-party import numpy as np import pandas as pd # Your own module from utils.helpers import load_config # Useful built-in modules import json # JSON serialisation import re # Regular expressions import math # Math functions import itertools # Iteration tools import functools # Higher-order functions import logging # Logging import asyncio # Async programming
9. File I/O
python# Read a file with open("data.txt", "r", encoding="utf-8") as f: content = f.read() # entire file as string # Write a file with open("output.txt", "w", encoding="utf-8") as f: f.write("Hello, World!\n") # JSON files with open("config.json", "r") as f: config = json.load(f) with open("config.json", "w") as f: json.dump(config, f, indent=2)
10. Comprehensions & Generators
python# Dictionary comprehension word_len = {word: len(word) for word in ["ai", "python", "llm"]} # Set comprehension unique_lengths = {len(word) for word in ["ai", "python", "llm"]} # Generator expression (memory-efficient) total = sum(x**2 for x in range(1_000_000)) # Generator function def token_stream(text: str): for word in text.split(): yield word # yields one token at a time for token in token_stream("hello world foo"): print(token)
11. Decorators
pythonimport time from functools import wraps def timer(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"{func.__name__} took {time.time() - start:.3f}s") return result return wrapper @timer def train_model(): time.sleep(1) return "done"
12. Type Hints (Python 3.5+)
pythonfrom typing import Optional, Union, Any def embed(text: str, model: str = "text-embedding-3-small") -> list[float]: ... def process(data: list[dict[str, Any]]) -> Optional[str]: ... def parse(value: Union[str, int]) -> str: return str(value)
13. Async Programming (Python 3.5+)
pythonimport asyncio import aiohttp async def fetch_completion(prompt: str) -> str: async with aiohttp.ClientSession() as session: async with session.post( "https://api.openai.com/v1/chat/completions", json={"model": "gpt-4o", "messages": [{"role": "user", "content": prompt}]} ) as resp: data = await resp.json() return data["choices"][0]["message"]["content"] async def main(): results = await asyncio.gather( fetch_completion("What is RAG?"), fetch_completion("What is LoRA?"), ) print(results) asyncio.run(main())
Quick Reference Summary
| Concept | Key Syntax |
|---|---|
| Variables | text text |
| Conditionals | text |
| Loops | text text |
| Functions | text |
| Classes | text text |
| Error handling | text |
| Imports | text text |
| List comprehension | text |
| Generator | text |
| Decorator | text |
| Type hints | text |
| Async | text text text |
Pro tip: Master these basics thoroughly — they underpin everything in Gen AI engineering, from writing LangChain pipelines to building custom training loops in PyTorch.
Learn more at Python Official Docs and Real Python.