How to Create a Virtual Environment in Python

💡 𝗪𝗵𝗮𝘁 𝗜𝘀 𝗮 𝗩𝗶𝗿𝘁𝘂𝗮𝗹 𝗘𝗻𝘃𝗶𝗿𝗼𝗻𝗺𝗲𝗻𝘁? 𝗮𝗻𝗱 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗧𝗲𝗰𝗵𝗻𝗶𝗾𝘂𝗲𝘀 𝘁𝗼 𝗖𝗿𝗲𝗮𝘁𝗲 𝗜𝘁 𝗶𝗻 𝗣𝘆𝘁𝗵𝗼𝗻. 🤔 Why do we need it? Suppose you are working on two projects on a single computer, but each project requires a different version of Python. How do you manage it? For more clarity — let’s say Project A requires Python 3.9 but Project B requires 3.12. This problem can be solved using Virtual Environment. 🧱 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗩𝗶𝗿𝘁𝘂𝗮𝗹 𝗘𝗻𝘃𝗶𝗿𝗼𝗻𝗺𝗲𝗻𝘁: Simply, a Virtual Environment is a separate workspace where you can easily install all the packages and other requirements needed for your project. There are different ways to create Virtual Environment in Python, but we’ll discuss only two of them. 1️⃣ Using Python Command To create a virtual environment using the Python command, write the below command: --> python -m venv my_env Then press Enter — this will create a virtual environment for you. Here, the name of the environment is my_env (you can choose any name you want). ⚙️ Activate Virtual Environment: Activation tells the computer to use the Python interpreter and packages inside this environment. To activate "my_env" use the command. --> my_env\Scripts\activate Replace my_env with your environment name — the rest stays the same. If you see your environment name inside parentheses like this: (my_env) — it means your Virtual Environment is successfully activated. 🧩 Deactivate Virtual Environment: When you deactivate it, the computer exits the Virtual Environment and uses the system’s default Python interpreter and packages. To deactivate, use: --> my_env\Scripts\deactivate After deactivation, you will no longer see (my_env) in the terminal. 🚀 Advantages of using Python for Virtual Environments: - You do not need to install Anaconda separately. 2️⃣ Creating Environment with Conda Command If you have Anaconda installed, the best way to create a Virtual Environment is by using the conda command. You can create and install any version of Python directly with one command: -->conda create -p my_env2 python==3.12 -y my_env2 → name of the new environment python==3.12 → specifies the Python version -y → automatically approves installation ⚙️ Activate the Virtual Environment: --> conda activate my_env2 🧩 Deactivate the Virtual Environment: --> conda deactivate my_env2 🚀 Advantages of using Conda Command: - Create environment and install specific Python version in one command. - No need to install Python separately. 🎯 This is all about Virtual Environment in Python. #python #virtualenvironment #pythonvenv #conda #anaconda #pythonenvironment #pythonprogramming #pythondeveloper #programming #machinelearning #coding #datascience #deeplearning

To view or add a comment, sign in

Explore content categories