Introduction to Python

PART 1

Section 1: Python and IDE Essentials

  • Introduction to Python
  • Installing Python
  • Setting up an Integrated Development Environment (IDE)
  • Introduction to Jupyter Lab, VS Code, Google Colab and Anaconda

Section 2: Working with Jupyter Lab

  • Understanding the basic syntax
  • How to write and execute code in Python
  • Setting up and organizing a Python project

What is Python?

Python is a versatile, high-level programming language known for its simplicity and readability. It is widely used for web development, data analysis, artificial intelligence, scientific computing, and more.

Why Learn Python?

  • Easy to read and write
  • Extensive libraries and frameworks
  • Strong community support
  • Great for beginners and professionals alike

Installing Python

Python can be installed on various operating systems, including Windows, macOS, and Linux.

Step 1: Download the Installer

  • Visit the official Python website: https://www.python.org/
  • Navigate to the Downloads section and choose the appropriate installer for your operating system.

Step 2: Run the Installer - Open the downloaded installer file. - Make sure to check the box that says “Add Python to PATH” during the installation process. This makes it easier to run Python from the command line.

Step 3: Verify the Installation - Open your command prompt (Windows) or terminal (macOS/Linux). - Type the following command to verify the installation:

python --version
  • You should see the version of Python you installed.

Congratulations! Python is now installed on your computer.

Setting up an Integrated Development Environment (IDE)

An IDE is a software application that provides comprehensive facilities to programmers for software development.

There are many IDEs available for Python. Two popular choices are VS Code and Jupyter Lab.

  1. Installing VS Code
  • Visit the Visual Studio Code website: https://code.visualstudio.com/
  • Download and install the version for your operating system.
  • Once installed, you can add Python support by installing the Python extension:
    • Open VS Code.
    • Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window.
    • Search for “Python” and install the extension provided by Microsoft.
    • Open a new Python file or notebook and start coding!
  • Tutorial: https://code.visualstudio.com/docs/python/python-tutorial
  • Key Features:
    • Extensions: VS Code has a vast library of extensions that enhance its functionality.
    • Integrated Terminal: You can run command-line tasks directly in VS Code.
  1. Installing Jupyter Lab
  • Jupyter Lab is a web-based interactive computing environment.

  • To install Jupyter Lab, you need to have Python installed. You can use pip, the Python package installer, to install Jupyter Lab:

        pip install jupyterlab
  • To start Jupyter Lab, open your command prompt (Windows) or terminal (macOS/Linux) and type: bash Jupyter Lab

  • This will open a new tab in your default web browser, where you can create and run Jupyter Labs.

  • Tutorial: https://jupyter.org/install

  • Key Features:

    • Interactive output: You can run code in real-time and see the results immediately.
    • Markdown support: You can write rich text, which makes it great for creating tutorials and educational materials.
    • Visualizations: You can embed visualizations and plots directly in the notebook.

Now you have both VS Code and Jupyter Lab set up for your Python development!

Setting up Google Colab

Google Colab, short for “Collaboratory,” is a free Jupyter Lab environment that runs entirely in the cloud. It is perfect for those who want to run Python code without having to set up anything on their local machines.

Step 1: Accessing Google Colab - Open your web browser and go to: https://colab.research.google.com/

Step 2: Creating a New Notebook - On the Google Colab homepage, you can either open an existing notebook or create a new one. - To create a new notebook, click on the “New Notebook” button.

Step 3: Using Google Colab - You can start writing and running Python code right away. - Google Colab provides free access to GPUs and TPUs, which can be used for more intensive computations.

Step 4: Saving Your Work - You can save your notebooks directly to Google Drive, which makes it easy to access them from any device. - To save your notebook, go to “File” -> “Save a copy in Drive…”

Key Features: - No installation required: You can start coding immediately without any local setup. - Cloud-based: Your notebooks are stored in Google Drive, making them easy to share and collaborate on. - Free access to GPUs and TPUs: This is particularly useful for machine learning and data science tasks.

Now you can use Google Colab to run Python code from anywhere, without worrying about setting up your local environment!

Setting up Anaconda (Additional Resources)

Anaconda is a distribution of Python and R for scientific computing and data science. It comes with many popular data science and machine learning libraries, as well as Jupyter Lab.

Step 1: Download Anaconda - Visit the Anaconda website: https://www.anaconda.com/products/distribution - Download the Anaconda installer for your operating system.

Step 2: Install Anaconda - Open the downloaded installer and follow the instructions. - During the installation, you can choose to add Anaconda to your PATH environment variable. This makes it easier to run Anaconda commands from the command line.

Step 3: Verify the Installation - Open your command prompt (Windows) or terminal (macOS/Linux). - Type the following command to verify the installation: bash conda --version - You should see the version of Conda that is installed.

Step 4: Launching Jupyter Lab from Anaconda - Anaconda Navigator is a graphical user interface that comes with Anaconda. It allows you to launch Jupyter Lab easily. - Open Anaconda Navigator from your applications menu. - In Anaconda Navigator, you will see Jupyter Lab listed. Click “Launch” to open it.

Now you have Anaconda installed, and you can use it to manage your Python environments and packages, as well as run Jupyter Labs!

Working with Jupyter Lab

Getting Started 1. Launching Jupyter Lab: - Open your command prompt (Windows) or terminal (macOS/Linux). - Type jupyter lab and press Enter. - A new tab will open in your default web browser showing the Jupyter Lab interface.

  1. Creating a New Notebook:
    • Click on the “New” button and select “Python 3” to create a new notebook.
    • You will see a new notebook with an empty code cell.
  2. Writing and Running Code:
    • Write your Python code in the code cells.
    • Execute the code by pressing Shift + Enter or clicking the “Run” button.
    • Example:
     print("Hello, Jupyter Lab!")
  3. Using Markdown Cells:
    • To add text, headers, lists, and other non-code content, use Markdown cells.

    • Change the cell type to Markdown by selecting “Markdown” from the dropdown menu.

    • Example of a Markdown cell:

      # This is a Header
      - This is a list item
          - Another list item

Example Workflow in Jupyter Lab


# Install necessary libraries
!pip install numpy pandas matplotlib seaborn

# Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


# Load a sample dataset from seaborn
data = sns.load_dataset('penguins')

# Display the first few rows of the dataset
print(data.head())
# Perform some basic data analysis
summary = data.describe()
print(summary)
# Create a simple plot
plt.figure(figsize=(10, 6))
plt.scatter(data['bill_length_mm'], data['bill_depth_mm'])
plt.title('Bill Length vs. Bill Depth')
plt.xlabel('Bill Length (mm)')
plt.ylabel('Bill Depth (mm)')
plt.show()

Documenting Your Analysis

  • We imported necessary libraries.
  • We loaded a sample dataset from the seaborn library and displayed the first few rows.
  • We performed a basic data analysis using the describe method.
  • We visualized the relationship between bill length and bill depth.

Advantages of Using Jupyter Lab

  • Interactive Coding: Run code and see results instantly, making it great for experimentation.
  • Documentation: Combine code and narrative text to create comprehensive and understandable documents.
  • Visualization: Easily integrate plots and charts to visualize your data.

Setting Up the Working Directory in Jupyter Lab

To ensure that Jupyter Lab uses the project directory as the working directory, you can use the os module to change the current working directory.

Step-by-Step Guide

  1. Import the os Module:
    • The os module provides a way of using operating system-dependent functionality.
  2. Define the Project Directory:
    • Specify the path to your project directory.
  3. Change the Current Working Directory:
    • Use os.chdir() to change the current working directory to the project directory.
  4. Verify the Current Working Directory:
    • Use os.getcwd() to print the current working directory and ensure it’s set correctly.

Example Code

Use python console or terminal.

import os

# Define project directory and subdirectories
project_dir = 'my_python_project'
folders = ['data', 'scripts', 'notebooks']

# Create the main project directory
if not os.path.exists(project_dir):
    os.makedirs(project_dir)

# Create subdirectories
for folder in folders:
    path = os.path.join(project_dir, folder)
    if not os.path.exists(path):
        os.makedirs(path)

# Check the created structure
!tree my_python_project

Go to your main project folder and open the terminal.

import os

# Define the project directory
project_dir = os.getcwd()

# Set the working directory to the project directory
os.chdir(project_dir)

# Check the current working directory
print("Current Working Directory:", os.getcwd())

example: save a file

# Save a Sample Dataset in the data Folder 
import pandas as pd

# Create a sample DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [24, 22, 23],
    'Grade': ['A', 'B', 'A']
}

df = pd.DataFrame(data)

# Display the DataFrame
print("Sample DataFrame:")
print(df)

# Define the path to save the CSV file
csv_file_path = os.path.join('data', 'students_data.csv')

# Save the DataFrame as a CSV file
df.to_csv(csv_file_path, index=False)

# Verify that the file has been saved
print(f"DataFrame saved as CSV file at: {csv_file_path}")