Python Programming Tutorials [Beginners to Advanced Level]

Python is a high-level programming language popular for its simplicity and readability. It is widely used in web development, data analysis, artificial intelligence, scientific computing, and more. If you want to become a Python and machine learning expert, you should start with the following Python programming tutorials, which are meant for beginners to advanced levels.

You should follow all the tutorials step-by-step.

Set Up Python

First, you should learn how to set up Python on your system.

Let me explain to you how to download and install Python on Windows, Linux, and macOS. As a developer, you might need to set up a Python environment on a new machine for a project.

Download and Install Python on Windows

Here are the steps to download and install Python on Windows OS.

You can also follow the video tutorial below.

Method 1: Using the Python Installer

  1. Download the Installer: Go to the official Python website and download the latest Python installer for Windows.
  2. Run the Installer: Open the downloaded file. Ensure you check the box that says “Add Python to PATH” before clicking “Install Now.”
  3. Verify Installation: Open Command Prompt and type python --version. You should see the installed Python version.

Method 2: Using Chocolatey

  • Install Chocolatey: Open PowerShell as an administrator and run:
Set-ExecutionPolicy AllSigned
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
  • Install Python: Once Chocolatey is installed, run:
choco install python
  • Verify Installation: Open Command Prompt and type python --version.

Download and Install Python on Linux

Method 1: Using Package Manager

  • Update Package List: Open Terminal and run:
sudo apt update
  • Install Python:
sudo apt install python3
  • Verify Installation: Type python3 --version in Terminal.

Method 2: Building from Source

  • Install Dependencies:
sudo apt install build-essential checkinstall
sudo apt install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
  • Extract and Install:
tar -xvf Python-<version>.tgz
cd Python-<version>
./configure --enable-optimizations
make
sudo make install
  • Verify Installation: Type python3 --version.

Download and Install Python on macOS

You can follow the steps below to download and install Python on macOS.

Also, check out the video tutorial below.

Method 1: Using the Python Installer

  1. Download the Installer: Visit the official Python website and download the latest Python installer for macOS.
  2. Run the Installer: Open the downloaded file and follow the instructions.
  3. Verify Installation: Open Terminal and type python3 --version.

Method 2: Using Homebrew

  • Install Homebrew: Open Terminal and run:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  • Install Python:
brew install python
  • Verify Installation: Type python3 --version in Terminal.

Setting Up an IDE

An Integrated Development Environment (IDE) makes coding easier by providing tools like syntax highlighting, code completion, and debugging. Popular IDEs for Python include:

Basic Syntax of Python Programming

Now, let me show you the basic syntax of Python programming.

Write Your First Program

Let’s start with a simple program that prints “Hello, World!” to the console.

print("Hello, World!")

Save this code in a file named hello.py and run it using the command:

python hello.py

You should see the output:

Hello, World!

Comments

Comments are lines in the code that are not executed. They are used to explain the code and make it more readable. Here is how you can add comments to Python code.

# This is a single-line comment

"""
This is a
multi-line comment
"""

Variables and Data Types in Python

In the next section, you should learn more about variables and data types in Python.

Variables

Variables are used to store data. In Python, you don’t need to declare the type of a variable. You can assign a value to it.

x = 5
name = "Alice"

Data Types

Python has several built-in data types:

  • Numbersintfloatcomplex
  • Stringsstr
  • Booleansbool
  • Listslist
  • Tuplestuple
  • Dictionariesdict
  • Setsset

Examples

Here is an example of how to use the Python data types.

# Integer
a = 10

# Float
b = 3.14

# String
c = "Hello"

# Boolean
d = True

# List
e = [1, 2, 3, 4, 5]

# Tuple
f = (1, 2, 3)

# Dictionary
g = {"name": "Alice", "age": 25}

# Set
h = {1, 2, 3, 4, 5}

Operators in Python

Now, let us understand the Python Operators.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

x = 10
y = 3

print(x + y)  # Addition
print(x - y)  # Subtraction
print(x * y)  # Multiplication
print(x / y)  # Division
print(x % y)  # Modulus
print(x ** y) # Exponentiation
print(x // y) # Floor Division

Comparison Operators

Comparison operators are used to compare two values.

x = 10
y = 3

print(x == y)  # Equal to
print(x != y)  # Not equal to
print(x > y)   # Greater than
print(x < y)   # Less than
print(x >= y)  # Greater than or equal to
print(x <= y)  # Less than or equal to

Logical Operators

Logical operators are used to combine conditional statements.

a = True
b = False

print(a and b)  # Logical AND
print(a or b)   # Logical OR
print(not a)    # Logical NOT

Control Flow Statements in Python

In the next section, you should read about the Control Flow Statements in Python.

If Statements

If statements in Python are used to execute a block of code based on a condition.

x = 10
y = 20

if x < y:
    print("x is less than y")
elif x == y:
    print("x is equal to y")
else:
    print("x is greater than y")

You can also see the output in the screenshot below:

python programming tutorials

For Loops

For loops in Python are used to iterate over a sequence (such as a list, tuple, or string).

# Loop through a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

# Loop through a range
for i in range(5):
    print(i)

You can see the output in the screenshot below:

python programming tutorial for beginners

While Loops

While loops in Python are used to execute a block of code as long as a condition is true.

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

Break and Continue

The break statement in Python is used to exit a loop prematurely, and the continue statement in Python is used to skip the current iteration and continue with the next iteration.

# Break example
for i in range(10):
    if i == 5:
        break
    print(i)

# Continue example
for i in range(10):
    if i == 5:
        continue
    print(i)

Functions in Python

Now, you should understand how to create and use Functions in Python.

Defining Functions

Functions are blocks of reusable code that perform a specific task.

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

print(greet("Alice"))

Default Arguments

Functions can have default arguments, which are used if no argument is provided.

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

print(greet())
print(greet("Bob"))

Variable-Length Arguments

Functions can accept a variable number of arguments using *args for positional arguments and **kwargs for keyword arguments.

def add(*args):
    return sum(args)

print(add(1, 2, 3, 4, 5))

Data Structures in Python

Now, let me explain a few advanced topics in Python related to data structures in Python.

Lists

Python Lists are ordered, mutable collections of items. They can store elements of different data types and allow for various operations like adding, removing, and accessing elements.

Creating a List

numbers = [1, 2, 3, 4, 5]

Accessing Elements

You can access elements in a list using their index. Python uses zero-based indexing.

numbers = [1, 2, 3, 4, 5]
print(numbers[0])  # Output: 1
print(numbers[-1]) # Output: 5 (last element)

Adding Elements

You can add elements to a list using append() or insert().

numbers = [1, 2, 3, 4, 5]
numbers.append(6)     # Adds 6 at the end
numbers.insert(0, 0)  # Inserts 0 at the beginning

Removing Elements

You can remove elements using remove()pop(), or del.

numbers = [1, 2, 3, 4, 5]
numbers.remove(3)  # Removes the first occurrence of 3
numbers.pop()      # Removes the last element
del numbers[0]     # Removes the element at index 0

Slicing

You can extract a portion of a list using slicing.

numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])  # Elements from index 1 to 3

Tuples

Python Tuples are similar to lists in but are immutable, meaning their elements cannot be changed after creation. They are useful for storing fixed collections of items.

Creating a Tuple

coords = (10, 20)

Accessing Elements

You can access elements in a tuple using their index.

print(coords[0])  # Output: 10
print(coords[1])  # Output: 20

Immutability

Tuples are immutable, so you cannot modify their elements.

# coords[0] = 15  # This will raise an error

Dictionaries

Dictionaries in Python are unordered collections of key-value pairs. They are mutable and allow for fast access to values based on their keys.

Creating a Dictionary

person = {"name": "Alice", "age": 25}

Accessing Elements

You can access values in a dictionary using their keys.

print(person["name"])  # Output: Alice
print(person["age"])   # Output: 25

Adding Elements

You can add key-value pairs to a dictionary.

person["city"] = "New York"

Removing Elements

You can remove key-value pairs using del.

del person["age"]How to Remove Multiple Keys from a Dictionary in Python?

Sets

Sets in Python are unordered collections of unique elements. They are useful for storing items without duplicates and for performing set operations like union, intersection, and difference.

Creating a Set

unique_numbers = {1, 2, 3, 4, 5}

Adding Elements

You can add elements to a set using add().

unique_numbers.add(6)

Removing Elements

You can remove elements using remove().

unique_numbers.remove(3)

Checking Membership

You can check if an element is in a set using the in keyword.

print(1 in unique_numbers)  # Output: True
print(7 in unique_numbers)  # Output: False

Arrays

In Python, an Array is a data structure that allows you to store a collection of elements of the same data type. Arrays are similar to lists in Python, but they are more efficient for certain operations and require less memory. Python provides the array module to create and manipulate arrays.

To create an array, you need to import the array module and specify the data type of the elements using a type code. For example, to create an array of integers, you can use the type code 'i'. Here’s an example:

import array as arr

numbers = arr.array('i', [1, 2, 3, 4, 5])

In this example, we import the array module and create an array called numbers using the array() function. The first argument is the type code 'i', indicating that the array will store integers. The second argument is a list of initial values to populate the array.

You can access elements of an array using indexing, just like with lists. The index starts from 0 for the first element and goes up to n-1 for the length of the array. n. For example:

print(numbers[0])  # Output: 1
print(numbers[2])  # Output: 3

Arrays support various operations and methods. Some commonly used ones include:

  • append(x)Appends the element x to the end of the array.
  • insert(i, x)Inserts the element x at the index i in the array.
  • remove(x)Removes the first occurrence of the element x from the array.
  • pop(i)Removes and returns the element at the index i from the array.
  • index(x)Returns the index of the first occurrence of the element x in the array.
  • count(x)Returns the number of occurrences of the element x in the array.

Here’s an example that demonstrates some of these operations:

numbers.append(6)
numbers.insert(0, 0)
numbers.remove(3)
value = numbers.pop(2)
index = numbers.index(4)
count = numbers.count(2)

print(numbers)  # Output: array('i', [0, 1, 2, 4, 5, 6])
print(value)    # Output: 2
print(index)    # Output: 3
print(count)    # Output: 1

Arrays in Python are efficient for storing and accessing elements of the same data type. They are particularly useful when you need to perform mathematical operations on large numeric data sets.

However, arrays are less flexible than lists because they are limited to a single data type and have a fixed size once created. If you need to store elements of different data types or require a more dynamic data structure, lists are often a better choice.

Modules and Packages in Python

Importing Modules

Python has a rich standard library that you can use to add functionality to your programs. You can import a module using the import statement.

import math

print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.141592653589793

Importing Specific Functions

You can also import specific functions or variables from a module.

from math import sqrt, pi

print(sqrt(16))  # 4.0
print(pi)        # 3.141592653589793

Creating Your Modules

You can create your modules by saving your Python code in a .py file and then importing it into another script.

# my_module.py
def greet(name):
    return f"Hello, {name}!"

# main.py
import my_module

print(my_module.greet("Alice"))

Packages

A package is a collection of modules. You can create a package by organizing your modules into directories.

my_package/
    __init__.py
    module1.py
    module2.py

You can then import the modules from the package.

from my_package import module1, module2

File Handling in Python

In this section, you should know about File Handling in Python.

Opening and Closing Files

You can open a file using the open function and close it using the close method.

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

Reading Files

There are various methods to read the content of a file.

  • read(): Reads the entire file
  • readline(): Reads one line at a time
  • readlines(): Reads all lines into a list
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

with open("example.txt", "r") as file:
    line = file.readline()
    while line:
        print(line, end="")
        line = file.readline()

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line, end="")

Writing Files

You can write to a file using the write or writelines methods.

with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a test file.")

with open("example.txt", "a") as file:
    file.write("\nAppending a new line.")

Error Handling in Python Programming

In the next section, you should learn how to handle errors in Python.

Try and Except

You can handle errors in Python using try and except blocks.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")

Finally

The finally block is executed regardless of whether an exception is raised or not.

try:
    file = open("example.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found!")
finally:
    file.close()

Raising Exceptions

You can raise exceptions using the raise statement.

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    return age

try:
    check_age(-1)
except ValueError as e:
    print(e)

Conclusion

In this tutorial, we covered the basics of Python programming, including setting up Python, basic syntax, variables and data types, operators, control flow, functions, data structures, modules and packages, file handling, and error handling.

Python Machine Learning Tutorials

Here is the list of machine learning tutorials in Python.

Python Data Science Tutorials

Here is the list of Python data science tutorials.

Other Python tutorials

PyGame tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.