Python is an interpreted, high-level, and general-purpose programming language known for its readability and concise syntax. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python’s extensive standard library, dynamic typing, and dynamic binding options make it highly attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components.

Few things I like about Python are

  • Readability and Syntax: Python’s syntax is simple and clean.
  • Extensive Standard Library: Python comes with a large standard library that includes modules for various tasks, such as connecting to web servers, reading JSON, and more.

Few things I dislike about Python are

  • Performance: Being an interpreted language, Python can sometimes be slower than compiled languages like Go or Rust.

Variables

In Python, variables are created when you assign a value to them. Python is dynamically typed, which means you do not need to declare variables before using them, or declare their type.

Syntax and Example:

x = 5  # x is of type int
y = "Hello, Python"  # y is of type str

PI = 3.14159  # Constant naming convention

Control Statements

Python uses control statements to direct the flow of execution, including if, elif, else, loops like for and while, and switch-like constructs through dictionaries.

Syntax and Example:

# If statement
if x > 0:
    print("x is positive")

# For loop
for i in range(10):
    print(i)

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

# Switch-like construct using dictionaries
def switch_case(argument):
    switch = {
        0: "zero",
        1: "one",
        2: "two",
    }
    return switch.get(argument, "Invalid argument")

Functions and Methods

Functions in Python are defined using the def keyword, and methods are functions that belong to an object.

Syntax and Example:

# Function definition
def greet(name):
    return "Hello, " + name + "!"

# Method definition
class Greeter:
    def __init__(self, name):
        self.name = name

    def greet(self):
        return "Hello, " + self.name + "!"

# function with multiple return values
def get_person():
    return "John", 30
name, age = get_person()

Data Structures (Classes)

Python provides several powerful data structures, such as lists, dictionaries, sets, and tuples, to store collections of data.

Syntax and Example:

# Class definition
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return "Hello, " + self.name + "!"

# data classes
from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int

p = Point(1, 2)
# Accessing fields
print(p.x)

Collections

Python provides a variety of built-in collection types, including lists, tuples, sets, and dictionaries. The collections module provides additional collection data types.

Syntax and Example:

# List
fruits = ["apple", "banana", "cherry"]
## Iterating over a list
for fruit in fruits:
    print(fruit)

# Dictionary
person = {"name": "John", "age": 30}
## Iterating over a dictionary
for key, value in person.items():
    print(key, value)

# Tuple
coordinates = (1, 2, 3)
## Accessing elements
print(coordinates[0])

# Set
unique_numbers = {1, 2, 3, 3}  # {1, 2, 3}

Error Handling

Python has built-in support for exceptions and uses a try-except block to handle errors.

Syntax and Example:

# Throw an exception
def divide(x, y):
    if y == 0:
        raise ZeroDivisionError("Cannot divide by zero")
    return x / y

# Catch an exception
try:
    result = divide(5, 0)
    print(result)
except ZeroDivisionError:
    print("Cannot divide by zero")

Concurrency

Python supports concurrency through different ways, including threads, the asyncio library, and multiprocessing.

Syntax and Example:

import threading

def print_numbers():
    for i in range(5):
        print(i)

# Using threads
thread = threading.Thread(target=print_numbers)
thread.start()

Ecosystem

Installation

Python can be installed from the official Python website or using package managers like Homebrew on macOS.

brew install python

Hello World

print("Hello, World!")

Build and Run

# Run the program
python hello.py

CLI

  • python <file-name.py>: Run a Python script
  • python -m venv <env-name>: Create a virtual environment

Package Management

pip is the package installer for Python. It allows you to install and manage additional libraries and dependencies that are not distributed as part of the standard library.

  • pip install <package-name>: Install a package

  • pip freeze: List installed packages

  • pip freeze > requirements.txt: Generate a requirements file

  • pip install -r requirements.txt: Install packages from a requirements file

  • virtualenv creates isolated Python environments to manage dependencies per project.

  • pipenv combines pip and virtualenv into one tool, aiming to simplify the workflow for managing project dependencies.

  • Flask - Lightweight WSGI web application framework
  • Django - High-level Python Web framework that encourages rapid development and clean, pragmatic design
  • NumPy - The fundamental package for scientific computing with Python
  • Pandas - Library providing high-performance, easy-to-use data structures, and data analysis tools
  • Requests - Elegant and simple HTTP library for Python, built for human beings
  • Scikit-learn - Machine learning library for Python
  • Matplotlib - Comprehensive library for creating static, animated, and interactive visualizations in Python
  • TensorFlow - An end-to-end open source platform for machine learning
  • PyTorch - An open source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing
  • Beautiful Soup - Library for pulling data out of HTML and XML files

Special Features

  • Versatility: Python can be used for web development, data analysis, artificial intelligence, scientific computing, and more.
  • Community and Libraries: The Python community is extensive, with a wealth of libraries and frameworks that extend its capabilities.
  • Interpretation and Dynamic Typing: These features make Python an excellent choice for rapid prototyping and scripts.