🐍

Python Programming Basics

Jun 16, 2025

Overview

This lecture covers the fundamentals of Python programming, progressing from installation and first programs to core concepts (variables, data types, control flow, functions, objects, and modules). It also introduces practical projects in web development, automation, and machine learning with relevant tools and libraries.

Getting Started with Python

  • Python is a widely used, versatile programming language for automation, AI, web applications, and more.
  • Download Python from python.org and install the latest version.
  • Install a code editor like PyCharm (Community Edition for free).
  • Ensure Python 3 is set as your project's interpreter (not Python 2).
  • Create and run your first Python program using the print function.

Core Programming Concepts

  • Python code is executed line by line by the interpreter.
  • A string is a sequence of characters (enclosed in quotes).
  • An expression is code that produces a value.
  • Variables temporarily store data in memory; assignment uses the = operator.
  • Data types: integer (no decimal), float (decimal), string (text), boolean (True/False).
  • Input is gathered with the input() function; use int(), float(), or bool() to convert strings to other types.
  • Use type() to check a variable's data type.

Working with Strings and Numbers

  • Single/double quotes for strings; triple quotes for multiline strings.
  • Indexing (e.g., string[0]) retrieves characters; negative indices count from the end.
  • Slicing (string[start:end]) returns substrings.
  • String methods: len(), upper(), lower(), find(), replace(), and in operator for membership.
  • Arithmetic operators: +, -, *, /, // (integer division), %, ** (exponentiation).
  • Operator precedence: ** > * / // % > + -

Control Flow

  • If, elif, and else statements control decisions.
  • Logical operators: and, or, not.
  • Comparison operators: >, >=, <, <=, ==, !=
  • Loops: while and for; while repeats until a condition is False, for iterates over sequences (strings, lists, ranges).
  • Use break to exit loops early; loops can have an else clause.

Data Structures

  • Lists: mutable, ordered collections (use index, slicing, methods like append, insert, remove, clear, pop, sort, reverse, copy, count).
  • Tuples: immutable, ordered sequences; only count and index methods.
  • Unpacking: Assign list/tuple values to multiple variables.
  • Dictionaries: key-value pairs; use keys to access/modify values.
  • Removing duplicates: check for existence before appending to a new list.
  • Two-dimensional lists and nested loops for working with matrices or grid data.

Functions and Modules

  • Functions are defined using def, take parameters, and can return values.
  • Use positional and keyword arguments; keyword arguments must follow positional ones.
  • Organize code in modules (separate .py files) and packages (folders with init.py).
  • Import modules or specific functions/classes with import or from ... import ...

Object-Oriented Programming

  • Define new types using classes; use PascalCase for class names.
  • Objects (instances) have attributes and methods.
  • Constructors (init) initialize object attributes.
  • Inheritance enables code reuse (e.g., Dog and Cat inherit from Mammal).

Error Handling and Comments

  • Use try-except blocks to handle exceptions (e.g., ValueError, ZeroDivisionError).
  • Comments start with #, should explain why/how, not what.

Standard and Third-Party Libraries

  • Python includes a standard library (e.g., math, random, pathlib).
  • Use pip to install additional packages from pypi.org (e.g., openpyxl for Excel).
  • Work with files and directories using pathlib.

Automation and Projects

  • Automate tasks like processing spreadsheets using openpyxl (read/write data, create charts).
  • Organize automation code into reusable functions.

Machine Learning Introduction

  • Machine learning models learn patterns from data and make predictions.
  • Typical workflow: import data, clean/prepare, split into training/testing, select algorithm, train, predict, evaluate accuracy.
  • Libraries: numpy (arrays), pandas (data frames), matplotlib (plots), scikit-learn (ML algorithms).
  • Use Jupyter notebooks for interactive data analysis.

Web Development with Django

  • Django is a popular web framework for rapid, structured web development.
  • Install Django, start a new project, and learn about its folder structure.
  • Use Django for building scalable, secure web applications.

Key Terms & Definitions

  • Variable — A label storing a value in memory.
  • String — A sequence of characters (text).
  • Boolean — Data type with values True or False.
  • List — Ordered, mutable collection.
  • Tuple — Ordered, immutable collection.
  • Dictionary — Unordered collection of key-value pairs.
  • Function — A reusable block of code with a specific task.
  • Class — Blueprint for creating objects with attributes and methods.
  • Module — A file containing Python code.
  • Package — A folder of modules (with init.py).
  • Constructor (init) — Method to initialize a new object.
  • Exception — An error that interrupts program flow.
  • Machine Learning Model — A trained program that makes predictions from data.

Action Items / Next Steps

  • Install Python, PyCharm, and set up your environment.
  • Complete suggested exercises (variables, input/output, weight converter, string slicing, shopping cart totals, duplicate removal).
  • Try automation tasks with openpyxl or use pathlib to explore directories.
  • Download Anaconda and practice with Jupyter Notebook and pandas loading/cleaning data.
  • Begin the first project: automate updating prices in Excel spreadsheets as shown.