Learn Computer Programming with Python for Free
The playlist for this course in YouTube is:- https://www.youtube.com/playlist?list=PLmlgUeL4GCpYcNm_jEIMWY-Lp5gxSHSAZ
Introduction
I have been studying Python since 2020, so I thought it would be a good idea to write a course on how to learn computer programming using Python.
Computer programming, often referred to as coding, is the process of creating a set of instructions that a computer can follow to perform specific tasks. These instructions, known as programs, are written in various programming languages that are more understandable to humans than machine code, which is directly executed by the computer’s central processing unit (CPU).
Programming involves designing and implementing programs, which are step by step specifications of procedures. Programmers use high level programming languages to write source code, which is then converted into machine language through a process called compiling. Some languages, like Python, use interpreters instead of compilers to execute the code.
There are hundreds of programming languages, each suited to different types of tasks. Some popular languages are Python, Javascript, C/C++, Java, and PHP. This course will focus specifically on the Python programming language, however.
The types of programming languages can be categorised as:-
· Machine language is a low level language consisting of binary code.
· Assembly language is a low level language compiled by an assembler.
· Procedural languages execute a set of procedures before running a program. Some procedural languages are Julia and Go.
· Scripting languages are interpreted languages that do not need to be compiled. Some scripting languages are Javascript and PHP.
· Functional languages build complex programs through functions. Some functional languages are Haskell and Scala.
· Object oriented languages build programs around collections of objects. Some object oriented languages are Java and Python.
Programming is essential for creating software that powers various devices and services that we use daily, such as phones, websites, and computers. It enables us to interact with technology and automate tasks, making our lives more efficient and productive.
Some skills required to be a good programmer are:-
· Writing clean and efficient code
· Problem solving
· Testing applications
· Fixing errors in the code
· Good communication skills
· Ability to work well within a team
· Patience and perseverance
How do we write code?
Coding is a skill learned and perfected over time, but everyone has to begin somewhere. There are several programming languages that are perfect for beginners, and Python is one of them.
It is important to have a good text editor that will enable you to actually write code. There are several good text editors that can be used, such as Visual Studio or Python’s IDE. Text editors will enable you to write and save your code to be run through an interpreter later.
See video on Microsoft Store and Python 3.13. (video 0, 1, and 2)
Video 0 :- https://youtu.be/jWCmzopH4CY
Video 1:- https://youtu.be/ad-LhU64DhU
Video 2:- https://youtu.be/UMnnSOVgdWw
The Python Programming Language
Python was implemented in 1989 by Guido van Russom at CWI in the Netherlands as a successor to ABC capable of exception handling and interfacing with the Amoeba operating system. Python was named after the BBC television show, Monte Python’s Flying Circus.
Python is a versatile, high level programming language that is used in programming projects from web development to machine learning and artificial intelligence (AI). Python supports multiple programming paradigms, including procedural, object oriented, and functional.
Python is a popular programming language for some of the following reasons:-
· Python has clean and straightforward syntax, using indentation instead of braces.
· Python is designed to be human readable, which helps to reduce errors, enhance collaboration, and facilitate maintenance.
· Python is a beginner friendly language because its syntax is simple, readable, and resembles pseudocode.
· Python is a general purpose language that can be used for web development, scientific computing, machine learning, and automation.
Writing your first program in Python
See video on writing your first program (video 3):- https://youtu.be/8IN6YV_QRfw
An exploration of Python variables and data types
Variables and data types are fundamental concepts that allow the programmer to store and manipulate data efficiently.
Variables are containers for storing data. Python variables do not require any explicit declaration of their type, with the type being inferred based on the value that they are assigned.
Types of variables in Python are:-
· String
· Integer
· Float
· Boolean
Rules for naming variables are:-
· Must start with a letter or underscore
· Cannot start with a number
· Can only contain alphanumeric characters or underscores.
· Case sensitive
Python has several built-in data types, which are:-
· Integers
· Float is a decimal or floating point number
· Complex contain real or imaginary types
· String is text that is enclosed in single or double quotes
· List is an ordered, mutable collection of elements
· Tuple is an ordered, immutable collection of elements
· Dictionary consists of key-value pairs
· Set consists of unordered, unique elements.
· Frozenset is an immutable version of a set
· Boolean is either true or false
· Nonetype is the absence of a value
See video on variables and datatypes (video 4):- https://youtu.be/Rgto__gWdTE
Basic input and output mechanisms in Python
Python provides several input and output mechanisms within the language, but this section of the course is going to cover the a few basic functions:-
· Input() is used to take the input from the user as a string.
· Print() is the most common way to display the output.
· The sys module handles command line inputs.
· The logging module is used for structured output.
See a video on input/output operations (video 5):- https://youtu.be/U0FTgpFxmBE
Commenting in Python programs
Comments in Python code are used to explain it, making it more readable and maintainable.
See video on comments and docstrings (video 6):- https://youtu.be/s1nHy4QscjI
The correct use of arithmetic operators in Python
Arithmetic operators are used with numeric values to perform common mathematical operations. The seven arithmetic operators used in Python are:-
· Addition (+)
· Subtraction (-)
· Multiplication (*)
· Division (/)
· Modulus (%)
· Exponentiation (**)
· Floor division (//)
See video on arithmetic operators (video 7):- https://youtu.be/k_cmYhH7-Bs
The correct use of comparison operators in Python
Comparison operators are used to compare two values and there are six comparison operators in Python:-
· Equal (==)
· Not equal (!=)
· Greater than (>)
· Less than (<)
· Greater than or equal to (>=)
· Less than or equal to (<=)
See video on comparison operators (video 8):- https://youtu.be/dSmSBOBGU5o
The correct use of logical operators in Python
Logical operators are used to combine conditional statements in Python:-
· And returns true if both statements are true.
· Or returns true if one of the statements is true.
· Not reverses the result. It returns false if the statement is true.
See video on logical operators (video 9):- https://youtu.be/O29l4USmc6M
The correct use of bitwise operators in Python
Bitwise operators perform operations at the bit level, manipulating individual bits of binary representations of numbers.
· (bitwise AND) & performs AND operation between corresponding bits of two operands. It returns a true value if both values are true.
· (bitwise OR) | performs OR operation between corresponding bits of two operands. It returns a false if both values are false.
· (bitwise XOR) ^ performs exclusive OR operation between corresponding bits of two operands. It returns a true if the two bits are different and a false if they are the same.
· (bitwise NOT) ~ inverts the bits of a single operand
· (left shift) << shifts bits to the left by a specified number of positions
· (right shift) >> shifts bits to the right by a specified number of positions
Bitwise operations can be used when programming:-
· Flags and permissions
· Swapping two numbers without a temp variable
· Checking to see if a number is a multiple of 2
· Bit masking
· Optimising modulo for powers of 2
See video on bitwise operations (video 10):- https://youtu.be/faSoyUBf-cA
Understanding conditional statements in Python
Conditional statements are used to execute specific blocks of code based on whether a condition evaluates to True or False. These statements allow for decision making in programs, making them dynamic and responsive.
The conditional statements in Python are:-
· If
· Elif
· Else
See video on conditional statements (video 11):- https://youtu.be/pqvXsA0q4o4
Understanding for loops in Python
The for loop is one of the most widely used control structures used in programming, being is used to execute a set of statements repetitively. We can use a for loop to iterate over a sequence of elements to perform a series of tasks a set number of times.
See video on for loops (video 12):- https://youtu.be/KntRSTHlqns
Understanding while loops on Python
A while loop is a control flow statement in programming that repeatedly executes a block of code as long as a specified condition evaluates to True.
See video on while loops (video 13):- https://youtu.be/LmZ34sAolSw
Understanding loop control keywords in Python
In Python, loop control keywords are used to manage the flow of for and while loops.
Four keywords are:-
· Break terminates a loop entirely
· Continue skips the current iteration and continues to the next iteration of the loop
· Pass does nothing, merely acting as a placeholder
· Else executes a block of code after the loop finishes, but only if the loop wasn’t terminated by a break
See video on control keywords (video 14):- https://youtu.be/qK9Vkin4ufQ
Functions in Python
Functions are blocks of reusable code that perform a specific task. They make work more modular, organised, and easy to maintain.
See video on creating a first function(video 15):- https://youtu.be/_kKQebPGuV8
Function Arguments
Function arguments are the values you pass to a function when calling it. Python supports several types of arguments, which allow for flexibility in how functions are defined and called, being:-
· Positional arguments are passed in the same order as defined in the function
· Keyword arguments specify arguments by name, regardless of their order
· Default arguments provide default values for parameters
· Variable length arguments accept any number of positional arguments as a tuple (*args) or a dictionary (**kwargs)
· Arguments can be combined, but the order must be: positional arguments, *args, keyword arguments, **kwargs
See video on function arguments (video 16):- https://youtu.be/pgdpRKYtB2s
Function return values
In Python, functions can return values using the return statement, allowing the programmer to send data back to the caller of the function. Some examples of return values are:-
· Returning a single value
· Returning multiple values
· Returning nothing
· Returning a data structure
· Returning functions
See video on return values (video 17):- https://youtu.be/ahJDV2MG_y4
Local versus global variables in Python
The Python programming language is composed of both local and global variables:-
· Local variables are declared inside a function and are only accessible within that function. They are created when the function is called and destroyed when the function ends.
· Global variables are declared outside of a function and are accessible throughout the program. Global variables exist as long as the program is running. To modify a global variable within a function, it must be declared as global within the function.
See video on local and global variables (video 18):- https://youtu.be/k--lmueLrd0
Understand Python’s anonymous function, lambda
The lambda function in Python is a small, anonymous function defined using the lambda keyword. It is often used for short, simple operations where defining a full function might feel excessive. Lambda functions can have any number of arguments, but only a single expression, which is evaluated and returned.
See video on lambdas (video 19):- https://youtu.be/rY8QwOrRLXQ
Using recursion in Python programming
Recursion is a process where a function calls itself to solve a problem by breaking it down into smaller instances of the same problem. This technique is commonly used in programming to handle:-
· Complex tasks
· Divide and conquer algorithms
· Fractal generation
· Backtracking
· Dynamic programming
· Tree and graph structures
The key components of a recursive function are:-
· The base case is the simplest scenario that does not require recursion. It acts as a termination condition to prevent infinite recursion.
· The recursive case calls itself within modified arguments, moving closer to the base case with each iteration.
Some important points that need to be considered when programming recursions are:-
· Recursive functions use more memory, as each call adds to the stack until the base case is reached.
· If the base case is not defined or reached, it can lead to a stack overflow error.
· Recursion can be inefficient and lead to stack overflows if not used carefully.
See video on recursions (video 20):- https://youtu.be/Mqzeb62_-aI
Data structures in Python
In previous lessons variables and data types were discussed. In this lesson, data structures will be discussed.
A data structure is a storage that is used to store and organise data. It is a way of arranging data on a computer so that it can be accessed and updated efficiently. A data structure can also be used for organising, processing and retrieving data. There are different basic and advanced data structures that have been written into almost every program or software system that has been developed. It is important, therefore, to have a good understanding and knowledge of data structures.
Some popular data structures are:-
· Lists are ordered, mutable, and can store heterogeneous elements. These data structures are ideal for creating dynamic arrays. Lists are used for storing sequential items.
· Tuples are ordered, immutable, and can store heterogeneous elements. These data structures are useful for fixed collections of items. Tuples are used to store collections of data and, since they are immutable, are good to store information that should not be changed.
· Sets are unordered, mutable, and store unique elements. These data structures are great for removing duplicates or performing set operations.
· Dictionaries are unordered, mutable, and store key value pairs. These data structures are perfect for mapping relationships.
· Python does not have a built-in stack data structure, but one can be built using a list or collection module, or queue module. Stacks are composed of lists or collections that follow the last in first out (LIFO) principle. These data structures are useful for undo operations or backtracking. Stacks are useful in syntax parsing and memory allocation in some operating systems and programs.
· Queues are collections that follow the first in first out (FIFO) principle. These data structures are suitable for scheduling or buffering. Queues are useful when a resource is shared between multiple users or when data is transferred asynchronously.
· Python does not have an inbuilt linked list, so it has to be custom built. A linked list is a list of nodes connected by pointers. This data structure is suitable for efficient insertion or deletion activities.
· Python does not have a built in graph structure. Graphs are made with dictionaries that have nodes that are connected by edges. These data structures are useful for representing networks or relationships. Graphs can be used in a wide variety of real world problems, such as social networks, transportation networks, and communication networks.
· Python does not have an inbuilt tree data structure, so it must be custom built. Trees are hierarchical structures with parent-child relationships. These data structures represent hierarchical data like file systems. These data structures represent hierarchical data like file systems. Trees assist in parsing, analysing, and evaluating expressions and statements in programming languages. Routing algorithms in computer networks often use tree-like structures to determine the best path for data packets.
See video on data structures (video 21):- https://youtu.be/-srH7oUJOcM
Iterating through collections in Python
There are various ways that we can iterate through collections like lists, tuples, dictionaries, sets, or custom objects.
Some common approaches to iterating through collections are:-
· The for loop is the most straightforward way to iterate through a collection.
· If you need both the index and the value while iterating, use the enumerate function.
· Use list comprehensions for concise iteration and transformation.
· Use the while loop if you want more control over the iteration.
· Manually iterate using the iter and next functions.
· Use the zip function to iterate through two or more collections simultaneously.
See video on iterating through collections (video 22):- https://youtu.be/4ieDkS8FP8c
Learn nesting and unpacking using Python
Nesting and unpacking in Python are powerful features that allow the programmer to work with complex data structures, such as lists, tuples, and dictionaries in an intuitive way.
· Nesting refers to placing one data structure inside another. Elements within a nested list (or a tuple or dictionary) can be accessed through indexes or keys.
· Unpacking allows the programmer to extract elements from a data structure and assign them to variables in a single step. You can unpack dictionaries using the ** operator.
See video on nesting and unpacking collections (video 23):- https://youtu.be/xOmf4O9DDZ0
Learn to read and write text files in Python
Reading and writing files in Python is flexible and straightforward.
It is possible to read, write, and append to txt and csv files.
· You can read files using the open() function with modes like ‘r’ (read) or ‘rb’ (read binary).
· To write to a file, use ‘w’ (write) or ‘a’ (append) mode. Writing overwrites the file, while appending adds to it.
· For non-text files like images or audio, use ‘rb’ (read binary) and ‘wb’ (write binary).
See video on reading, writing, and appending csv and txt files (video 24):- https://youtu.be/THHUyeWboPY
Use error handling techniques in Python
Error handling is primarily managed by try, except, else, and finally blocks. These constructs enable the programmer to handle exceptions and ensure the program continues running or exits cleanly.
Logging is a second way that errors can be handled. Logging can be used as an alternative to the print function. Logging allows the programmer to set different levels of severity, such as DEBUG, INFO, WARNING, ERROR, CRITICAL, thus allowing the programmer to control the granularity of the messages. The logger will filter the messages based on their importance, but the print function outputs everything indiscriminately.
While the print function is simple and useful for quick debugging, logging provides a robust, scalable, and professional solution for managing output in Python applications.
See video on error handling (video 25):- https://youtu.be/vxo7NTQ6ksg
Understanding concurrency in Python
Concurrency refers to the ability to execute multiple tasks simultaneously, improving the efficiency and responsiveness of programs. Python provides several ways to achieve concurrency to include:-
· Threading allows you to run multiple threads within a single process. Threads share the same memory space, making it lightweight but potentially prone to race conditions. Threading is easy to use and is good for I/O bound tasks. Threading is limited by the Global Interpreter Lock (GIL), which prevents true parallelism for CPU bound tasks.
· Multiprocessing creates separate processes, each with its own memory space, bypassing the GIL and enabling true parallelism. Multiprocessing takes higher memory usage due to separate processes.
· Asynchronous programming allows the handling of I/O bound tasks efficiently using co-routines. Asynchronous programming requires a different programming paradigm and is not suitable for CPU bound tasks.
The following tasks are suitable for concurrency:-
· I/O bound tasks use threading and asynchronous programming.
· CPU bound tasks use multiprocessing.
· Combined approaches can be used for mixed workloads.
See video on concurrency (video 26):- https://youtu.be/vxo7NTQ6ksg
Debugging in Python
Debugging in Python can be accomplished using the built-in pdb module, which provides an interactive source code debugger. It allows for setting breakpoints, stepping through code, inspecting stack frames, and evaluating Python code within any stack frame.
Common commands in the pdb module are:-
- To execute the next line of code — n (next)
- Step into a function call — s (step)
- Continue execution until the next breakpoint — c(continue)
- Exit the debugger — q(quit)
- Show the current code context — l(list)
- Print the value of a variable — p(variable)
- Set a breakpoint to a specific line — b(line)
- Clear a specific breakpoint — cl(breakpoint)
- Execute a Python expression — !(expression)
See video on debugging (video 27):- https://youtu.be/mTUjjUClWhc
Using libraries and modules in Python
Python comes with a number of libraries that are built into the programming language.
Some of the common inbuilt libraries in Python are:-
· To interact with the operating system — os
· To access system specific parameters and functions — sys
· To read and write csv files — csv
· To perform mathematical operations — math
· To generate random numbers — random
· To perform statistical operations — statistics
· To perform decimal arithmetic — decimal
· To work with rational numbers — fractions
· To perform regular expression operations — re
· To work with common string operations and constants — string
· To handle date and time — datetime
· To work with time related functions — time
· To perform calendar related operations — calendar
The great thing about these in-built libraries is the fact that they are already installed in the Python programming language, so there is no need to install them when Python is installed on the computer.
These in-built libraries are accessed using the import statement in Python.
See video on Python’s inbuilt statistics module (video 28):- https://youtu.be/qq4gADRVmo0
Create your own library to use in a Python program
It is a relatively easy matter to create your own library to use in a Python program:-
1. Create the library file.
2. Create a test file to test the functions in the library.
3. Make the library a package if you want to reuse it.
See video on creating a Python library (video 29):- https://youtu.be/Ls2TyMkEG6U
Explore object oriented programming (OOP) in Python
OOP in Python is a programming paradigm that organises code into reusable objects that combine data (attributes) and behaviour (methods):-
· A class is a blueprint for creating objects. It defines attributes and methods.
· An object is an instance in a class.
· Encapsulation is bundling data and methods together, restricting access to some components.
· Inheritance is creating a new class from an existing class to reuse or extend functionality.
· Polymorphism is using a unified interface for different data types or interfaces.
The benefits of OOP in Python are:-
· Classes and objects can be reused across projects.
· Code is organised into logical sections.
· It is easy to extend and maintain as projects grow.
· OOP hides complex implementation details.
OOP is used to write programs for real world entities, to organise code for better readability, or to manage complex systems.
OOP is common in Python because it allows developers to create reusable, modular, and organised code by encapsulating data and behaviour into objects.
OOP is common in Python because:-
· Python’s syntax for OOP is simple and intuitive.
· Many Python libraries, such as Tensorflow, are built using OOP.
· OOP helps manage larger codebases by organising code into larger structures.
· Python’s community widely adopts and promotes OOP practices.
See video on OOP (video 30):- https://youtu.be/sh6zzZr2BW0
Building a virtual environment in Python
A virtual environment is an isolated environment that allows the programmer to manage the dependencies for a specific project without affecting other projects or the global Python installation.
In Python, a virtual environment can be set up using the inbuilt venv module.
Complete real world projects
See video on making a book store using OOP (video 31):- https://youtu.be/W6SMV8yvSC0
See video on the hangman game (video 32):- https://youtu.be/TQKZfaMAR7U
See video in greeting with a GUI (video 33):- https://youtu.be/rH5X6wA7xMo
