How to Install Python on Ubuntu and Build Your First Python Project

Introduction


Python is one of the most popular programming languages for beginners, software developers, data analysts, and system administrators. Its readable syntax, extensive collection of libraries, and broad range of applications make it an excellent choice for learning programming. Ubuntu, a widely used Linux distribution, provides a convenient environment for developing Python applications because it includes powerful command-line tools, package management, and access to open-source development software.


Whether you want to create websites, automate repetitive tasks, analyze data, develop command-line applications, or explore artificial intelligence, Python offers tools that can help you get started. Ubuntu makes it possible to install development utilities, organize projects, manage dependencies, and execute Python programs directly from the terminal.


However, installing Python correctly is important. Ubuntu uses Python for certain system tools, so changing or removing the system-managed Python installation can cause problems. Beginners should learn how to check their installed Python version, use the package manager appropriately, and create isolated environments for individual projects.


This guide explains how to install and verify Python on Ubuntu, write your first Python program, use a code editor, create virtual environments, install external libraries, troubleshoot common errors, and build a practical project. Each section includes examples you can follow on your own computer.


By the end of this tutorial, you will understand the basic steps involved in setting up a Python development environment on Ubuntu and will be ready to begin creating your own applications.


1. What Is Python and Why Use It on Ubuntu?


Python is a high-level, general-purpose programming language designed to make code relatively easy to read and write. Developers use it for web development, automation, testing, data analysis, scientific computing, machine learning, and many other tasks.


One of Python's main advantages is its straightforward syntax. For example, a program that prints a message can contain only one line:


print("Hello, Ubuntu!")



This simplicity allows beginners to concentrate on programming concepts instead of learning complicated syntax immediately.


Python is also supported by a large ecosystem of third-party libraries. These libraries provide reusable functionality for working with web requests, databases, numerical calculations, data visualization, and other tasks.


Ubuntu complements Python well because it offers a powerful terminal, Git, development editors, compilers, and package management tools. Many Python developers use Ubuntu for local development, remote servers, testing environments, and deployment workflows.


Common uses of Python on Ubuntu include:


Automating file management and routine system tasks.

Building web applications and application programming interfaces.

Processing CSV files, JSON documents, and other datasets.

Developing command-line utilities.

Writing automated tests for software projects.

Creating scientific and mathematical applications.

Experimenting with machine learning and artificial intelligence.

Managing development workflows and server-side operations.


Python is not limited to Linux. Programs can often run on Windows and macOS as well, although operating-system-specific commands, dependencies, and filesystem behavior may require adjustments.


For a beginner using Ubuntu, Python provides an accessible introduction to programming while leaving room to explore more advanced development fields later.


2. Check Whether Python Is Already Installed


Before installing anything, check whether Python 3 is already available on your Ubuntu computer.


Open the terminal by pressing Ctrl + Alt + T.


Run:


python3 --version



If Python is installed, the terminal displays a version number, such as Python 3.x.y. The exact version depends on your Ubuntu release and installed packages.


You can also identify the executable path:


command -v python3



On a standard Ubuntu installation, this commonly returns:


/usr/bin/python3



The exact path may differ if you use a custom Python installation or environment.


Next, check whether pip is available:


python3 -m pip --version



Pip is Python's commonly used package installer. If this command reports that the module is missing, you may need to install Ubuntu's appropriate pip package.


You can also inspect the installed Python version through the interactive interpreter:


python3



At the Python prompt, enter:


print("Python is working!")



To leave the interactive interpreter, type:


exit()



Checking your existing installation helps you avoid installing unnecessary software or accidentally creating multiple conflicting Python configurations.


Important: Do not remove or replace Ubuntu's system-managed Python just because you want a newer version. System tools may depend on the distribution's Python packages. For application development, use a virtual environment or a separately managed Python installation when a different version is required.


3. Update Ubuntu Before Installing Development Tools


Keeping your package information current helps Ubuntu locate the latest package versions available from your configured repositories.


Open the terminal and run:


sudo apt update



Ubuntu refreshes the package index from its configured sources.


If you want to install available system updates, you can use:


sudo apt upgrade



Review the proposed changes before confirming the operation. A full system upgrade is not required every time you install Python, but regular maintenance can improve security and compatibility.


Now install Python 3 if it is not already present:


sudo apt install python3



After the installation finishes, verify the result:


python3 --version



If you are using a standard supported Ubuntu release, the package manager should select the Python version provided for that release.


Ubuntu's package repositories are generally a sensible starting point because they manage software dependencies and integrate packages with the operating system.


If you require a Python version newer than the one available in your release, investigate a suitable version-management approach rather than replacing the system interpreter. Different approaches have different maintenance and security implications, so choose one that fits your development requirements.


4. Install Pip and Virtual Environment Support


Python includes a standard library, but many projects require external packages. Pip helps install those packages, while virtual environments isolate dependencies between projects.


On Ubuntu, install the relevant packages with:


sudo apt install python3-pip python3-venv



The package names may vary for certain specialized Python versions or installations. If APT reports that a package cannot be found, check the package names supported by your Ubuntu release and the repositories you have enabled.


Verify pip:


python3 -m pip --version



Check that Python's virtual-environment module is available:


python3 -m venv --help



If the command displays help information, the module is available.


A virtual environment is a separate directory containing an environment-specific Python setup and package installation location. It allows each project to use its own dependencies without unnecessarily changing the system-wide Python environment.


For example, one application might need one version of a web framework while another project requires a different version. Virtual environments make it easier to keep those dependencies separate.


You should generally prefer project-specific environments instead of installing application libraries globally with administrator privileges.


This is especially important on Ubuntu, where the system Python installation may be managed by the operating system.


5. Create Your First Python Project


Now that Python is installed, create a dedicated directory for your first project.


Run:


mkdir -p ~/projects/hello-python

cd ~/projects/hello-python



The first command creates the directory structure if it does not already exist. The second command changes the current working directory.


Create a Python source file:


nano hello.py



Enter the following code:


def main():

    print("Hello, Ubuntu!")

    print("I am learning Python programming.")


if __name__ == "__main__":

    main()



Save the file and exit Nano.


Now execute the program:


python3 hello.py



The terminal should display:


Hello, Ubuntu!

I am learning Python programming.



Let's examine how the code works.


The def keyword defines a function named main. A function groups instructions under a name so that they can be called when needed.


The print() function displays text in the terminal.


The final conditional checks whether the file is being executed directly rather than imported as a module. If it is being executed directly, Python calls main().


This pattern is common in Python scripts because it separates reusable code from the program's main execution logic.


You have now written and executed your first Python program on Ubuntu.


6. Understand Basic Python Syntax


Before building larger applications, learn a few fundamental Python concepts.


Variables


Variables store values that you can use later.


name = "Alex"

age = 25

language = "Python"


print(name)

print(age)

print(language)



Python determines the type of a variable from the value assigned to it. In this example, name and language contain strings, while age contains an integer.


You can use variables to personalize output:


name = "Alex"


print(f"Welcome, {name}!")



The f prefix creates an f-string, allowing expressions inside braces to be inserted into the text.


User Input


Python's input() function reads text entered by the user.


name = input("What is your name? ")

print(f"Hello, {name}!")



When the program runs, it waits for the user to enter a response.


Remember that input() returns a string. If you want to use the input as a number, you must convert it and handle invalid input appropriately.


For example:


age_text = input("Enter your age: ")


try:

    age = int(age_text)

    print(f"Next year, you will be {age + 1}.")

except ValueError:

    print("Please enter a valid whole number.")



This program converts the entered text to an integer and handles input that cannot be converted.


Conditional Statements


Conditions allow programs to make decisions.


temperature = 30


if temperature > 25:

    print("The weather is warm.")

else:

    print("The weather is cool.")



Python uses indentation to identify blocks of code. Consistent indentation is essential because incorrectly indented statements can cause syntax errors or change the program's behavior.


Loops


Loops repeat instructions.


for number in range(1, 6):

    print(number)



This program displays the numbers from 1 through 5.


Learning variables, input, conditions, and loops gives you the foundation needed to build more practical Python applications.


7. Create and Activate a Python Virtual Environment


A virtual environment is one of the most useful tools for Python development on Ubuntu.


It isolates project dependencies so that installing a package for one application does not automatically change the packages used by another project.


From your project directory, run:


python3 -m venv .venv



This creates a virtual environment in a directory named .venv.


Activate it:


source .venv/bin/activate



Your terminal prompt may change to indicate that the environment is active.


Now check the Python executable:


python --version



Within the activated environment, python should normally refer to the environment's Python interpreter.


You can check its location with:


which python



The path should point into the project's .venv directory.


To leave the environment, run:


deactivate



You can reactivate it whenever you return to the project.


Virtual environments are local development tools and should usually not be committed to Git. Add .venv/ to your project's .gitignore file.


For example:


.venv/

__pycache__/

*.py[cod]

.env



The .env pattern is useful when projects use local environment files, but remember that ignoring a file does not automatically protect a secret that has already been committed.


For most beginners, using one virtual environment per project is a simple and effective approach to dependency management.


8. Install Python Packages with Pip


Many Python projects depend on external libraries that provide functionality beyond the standard library.


Pip can install these packages from package indexes such as the Python Package Index, commonly known as PyPI.


First, activate your virtual environment:


source .venv/bin/activate



Then install a package. For example:


python -m pip install requests



The Requests library makes it easier to send HTTP requests from Python applications.


You can verify that the package is installed:


python -m pip show requests



You can also test an import:


python -c "import requests; print(requests.__version__)"



The output displays the installed Requests version.


Using python -m pip is helpful because it associates pip with the Python interpreter you intend to use.


If you run the command inside an activated virtual environment, it will generally install the package into that environment.


To record a project's installed dependencies, you can use:


python -m pip freeze > requirements.txt



This creates a list of installed package versions in a file named requirements.txt.


Another computer can install the listed packages using:


python -m pip install -r requirements.txt



For small projects, this approach is convenient. Larger applications may benefit from more deliberate dependency management and lockfiles.


Avoid using sudo pip install to install ordinary project dependencies into Ubuntu's system Python. Use a virtual environment or another supported package-management approach instead.


9. Choose a Code Editor for Python Development


You can write Python programs using a simple text editor, but a programming-focused editor provides features that make development easier.


Popular options include Visual Studio Code, PyCharm, and terminal editors such as Vim and Nano.


Visual Studio Code is a flexible option because it supports Python through an extension and integrates well with Ubuntu's terminal and Git tools.


To open

Comments

Popular posts from this blog

How to Install and Use Visual Studio Code on Ubuntu for Programming

How to Install and Use Git on Ubuntu for Version Control