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
- Download the Installer: Go to the official Python website and download the latest Python installer for Windows.
- Run the Installer: Open the downloaded file. Ensure you check the box that says “Add Python to PATH” before clicking “Install Now.”
- 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 --versionin 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- Download Python Source: Go to the Python Downloads page and download the source code.
- 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
- Download the Installer: Visit the official Python website and download the latest Python installer for macOS.
- Run the Installer: Open the downloaded file and follow the instructions.
- 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 --versionin 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.pyYou 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:
- Numbers:
int,float,complex - Strings:
str - Booleans:
bool - Lists:
list - Tuples:
tuple - Dictionaries:
dict - Sets:
set
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 DivisionComparison 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 toLogical 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 NOTControl 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:

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:

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 += 1Break 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 beginningRemoving 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 0Slicing
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 3Tuples
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: 20Immutability
Tuples are immutable, so you cannot modify their elements.
# coords[0] = 15 # This will raise an errorDictionaries
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: 25Adding 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: FalseArrays
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: 3Arrays support various operations and methods. Some commonly used ones include:
append(x)Appends the elementxto the end of the array.insert(i, x)Inserts the elementxat the indexiin the array.remove(x)Removes the first occurrence of the elementxfrom the array.pop(i)Removes and returns the element at the indexifrom 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 elementxin 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: 1Arrays 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.141592653589793Importing 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.141592653589793Creating 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.pyYou can then import the modules from the package.
from my_package import module1, module2File 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 filereadline(): Reads one line at a timereadlines(): 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.
- Why Is Python Used for Machine Learning?
- Fastest Sorting Algorithm in Python
- How Much Do Machine Learning Engineers Make?
- What Is The Future of Machine Learning
- Machine Learning Life Cycle
- Machine Learning for Managers
- Machine Learning for Business Analytics
- Machine Learning Scientist Salary
- 9 Python Libraries for Machine Learning
- Statistical Learning vs Machine Learning
- Computer Vision vs Machine Learning
- Machine Learning vs Neural Networks
- What is Quantization in Machine Learning?
- Machine Learning for Document Classification
- Machine Learning Image Recognition
- Machine Learning Techniques for Text
- Price Forecasting Machine Learning
- Price Optimization Machine Learning
- Machine Learning for Signal Processing
- Predictive Maintenance Using Machine Learning
- Data Preprocessing in Machine Learning
- Customer Segmentation Machine Learning
- Machine Learning Image Processing
- Genetic Algorithm Machine Learning
- Interpretable Machine Learning with Python
- Feature Extraction in Machine Learning
- Machine Learning Design Patterns
- 100 Best Python Data Science Interview Questions and Answers (2025)
- Machine Learning Engineering with Python
- Machine Learning Product Manager
- What is Regression in Machine Learning
- 10 Machine Learning Use Cases Transforming Industries Today
- 15 Machine Learning Project Ideas for Aspiring Data Scientists
- What is Inference in Machine Learning?
Python Data Science Tutorials
Here is the list of Python data science tutorials.
- Data Science vs Machine Learning
- Machine Learning Engineer vs Data Scientist
- 10 Best Python Libraries for Data Science
Other Python tutorials
- Convert Epoch to Datetime in Python
- Python Pretty Print JSON
- ValueError: math domain error in Python
- Convert Degrees to Radians in Python
- How to Take Continuous Input in Python?
- Python Code to Print a Binary Tree
- Print Quotes in Python
- Python Program for Bubble Sort
- Python Program for a Diamond Pattern
- How to Print in the Same Line in Python
- Replace Whitespaces with Underscore in Python
- How to Skip a Line in Python
- Extend vs Append in Python
- How to Build a Perceptron in Python
- Python Program for Selection Sort
- Python Program to Count Upper and Lower Case Characters
- Capitalize First and Last Letters of Each Word in a String in Python
- Traffic Signal Program in Python
- Python – stdin stdout and stderr
- NameError: name is not defined in Python
- Fix SyntaxError: invalid character in identifier in Python
- Remove Unicode Characters in Python
- Exit an If Statement in Python
- Fix the Python 3 pickle type error: a bytes-like object is required not ‘str
- Python Program to Get the Last Day of the Month
- Program to Find the Area of a Rectangle in Python
- Remove Character from String Python By Index
- Python Increment By 1 | Python Decrement by 1
- Call By Value and Call By Reference in Python
- Escape Sequence in Python
- Convert PDF to Docx in Python
- Fix Invalid Syntax in Python
- Use Switch Case in Python with User Input
- Get Absolute Value in Python Without Using Abs
- Perform Word Count in a Python Program
- Write a Program to Calculate Simple Interest in Python
- Identifier in Python
- Python Subtraction Program
- How to Replace Multiple Spaces with a Single Space in Python
- Find the Area of the Triangle in Python
- Print 1 12 123 Pattern in Python
- Get IP From a URL in Python
- Area of a Circle in Python
- How to Multiply in Python
- Convert DateTime to UNIX Timestamp in Python
- Interfaces in Python
- Command Errored Out with Exit Status 1 in Python
- Priority Queue in Python
- Fibonacci Series Program in Python
- Exponents in Python
- Happy Birthday: Code in Python
- end in Python
- Find the Area of a Square in Python
- Save Images in Python
- Python Hello World Program
- Square Root in Python
- Python Split Regex
- Split a Sentence into Words in Python
- Percentage Symbol (%) in Python
- Send Emails Using Python
- Access Modifiers in Python
- Fastest Sorting Algorithm in Python
- raw_input Function in Python for User Input
- Get the Current Date and Time in Python
- Difference Between = and == in Python
- Difference Between {} and [] in Python
- Comment Out a Block of Code in Python
- Difference Between “is None” and “== None” in Python
- Python 3 vs Python 2
- Python vs C#
- Use Single and Double Quotes in Python
- Comment Out Multiple Lines in Python
- Difference Between is and == in Python
- Is Python an Interpreted Language?
- Is Python a Compiled Language?
- Is Python a Scripting Language?
- Is Python a High Level Language?
- JavaScript vs Python for Web Development
- Is Python an Object-Oriented Language?
- Compare Lists, Tuples, Sets, and Dictionaries in Python
- What Is the Best Way to Learn Python?
- Python / vs //
- Should I Learn Java or Python?
- Should I Learn Python or C++?
- PyCharm vs. VS Code for Python
- Python input() vs raw_input()
- Difference Between *args and **kwargs in Python
- Is Python a Good Language to Learn?
- Python Return Statement
- Validate Passwords in Python
- Get the Day of the Week from a Date in Python
- Validate Email Addresses in Python
- Binary Search in Python
- Indent Multiple Lines in Python
- Python Screen Capture
- How to read video frames in Python
- How to Check Python Version
- What Does // Mean in Python? (Floor Division with Examples)
- Understand __init__ Method in Python
- Understand for i in range Loop in Python