Skip to content

Python

Python is a high-level, interpreted, general-purpose programming language with a design philosophy that emphasizes code readability. Created by Guido van Rossum and first released in 1991, Python has become one of the most popular languages in the world due to its simplicity, versatility, and wide range of applications.

Key Features

1. Clear and Readable Syntax

Python uses indentation to define code blocks, which enforces a consistent coding style and improves readability.

def calculate_average(numbers):
    if not numbers:
        return 0
    return sum(numbers) / len(numbers)

# Example of using conditionals
age = 18
if age >= 18:
    print("Of legal age")
else:
    print("Underage")

2. Dynamic and Strong Typing

Python is a dynamically typed language, which means that a variable's type is determined at runtime. At the same time, it is strongly typed, which means that object types do not change implicitly.

x = 10          # x is an integer
x = "Python"    # now x is a string
# x + 5         # This would raise an error: cannot concatenate 'str' and 'int'

3. Interpreted

Python is an interpreted language, which means the code is executed line by line by an interpreter, without the need for prior compilation to machine code.

4. Multi-paradigm

Python supports multiple programming paradigms:

  • Imperative Programming: Based on commands that change the program's state.
  • Object-Oriented Programming: Based on classes and objects.
  • Functional Programming: Treating functions as first-class citizens.
  • Procedural Programming: Based on procedures or routines.

5. Comprehensive Standard Library

Python comes with an extensive standard library that offers modules and packages for various tasks, from file handling to web development.

Basic Syntax

Variables and Data Types

# Numbers
integer = 10
floating_point = 3.14
complex_number = 1 + 2j

# Strings
text = "Python"
multiline_text = """This is a
text with multiple
lines"""

# Booleans
is_true = True
is_false = False

# Lists (mutable)
my_list = [1, 2, 3, 4, 5]
mixed_list = [1, "two", 3.0, [4, 5]]

# Tuples (immutable)
my_tuple = (1, 2, 3)

# Dictionaries
my_dictionary = {"key": "value", "name": "Python"}

# Sets
my_set = {1, 2, 3, 4, 5}

Control Structures

Conditionals

# If-elif-else
age = 20
if age < 18:
    print("Underage")
elif age == 18:
    print("Just reached legal age")
else:
    print("Of legal age")

# Ternary operator
status = "Of legal age" if age >= 18 else "Underage"

Loops

# For loop
for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

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

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

# Break and continue
for i in range(10):
    if i == 3:
        continue  # Skips to the next iteration
    if i == 7:
        break     # Exits the loop
    print(i)

Functions

# Function definition
def greet(name):
    return f"Hello, {name}!"

# Function call
message = greet("Python")
print(message)  # Output: Hello, Python!

# Default parameters
def custom_greeting(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# Args and kwargs
def example_args_kwargs(*args, **kwargs):
    print(f"Args: {args}")
    print(f"Kwargs: {kwargs}")

example_args_kwargs(1, 2, 3, name="Python", version=3.9)

Lambda Functions

# Lambda function (anonymous)
double = lambda x: x * 2
print(double(5))  # Output: 10

# Usage with higher-order functions
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
doubled = list(map(lambda x: x * 2, numbers))

Object-Oriented Programming

Classes and Objects

class Person:
    # Class attribute
    species = "Homo sapiens"

    # Constructor method
    def __init__(self, name, age):
        # Instance attributes
        self.name = name
        self.age = age

    # Instance method
    def introduce(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

    # Class method
    @classmethod
    def create_from_birth_year(cls, name, birth_year):
        from datetime import date
        age = date.today().year - birth_year
        return cls(name, age)

    # Static method
    @staticmethod
    def is_adult(age):
        return age >= 18

# Creating instances
person1 = Person("Ana", 30)
person2 = Person.create_from_birth_year("Carlos", 1995)

print(person1.introduce())  # Output: Hello, my name is Ana and I am 30 years old.
print(Person.is_adult(17))   # Output: False

Inheritance

class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

# Creating instances
rex = Dog("Rex")
felix = Cat("Felix")

print(rex.name)         # Output: Rex
print(rex.make_sound()) # Output: Woof woof!
print(felix.make_sound()) # Output: Meow!

Encapsulation

class BankAccount:
    def __init__(self, owner, initial_balance=0):
        self.owner = owner
        self.__balance = initial_balance  # Private attribute

    def deposit(self, amount):
        if amount > 0:
            self.__balance += amount
            return True
        return False

    def withdraw(self, amount):
        if 0 < amount <= self.__balance:
            self.__balance -= amount
            return True
        return False

    def check_balance(self):
        return self.__balance

# Creating an account
account = BankAccount("João", 1000)

# Accessing public methods
account.deposit(500)
account.withdraw(200)
print(account.check_balance())  # Output: 1300

# Trying to access a private attribute
# print(account.__balance)  # This would raise an AttributeError

Advanced Features

Generators

# Generator function
def counter(maximum):
    count = 0
    while count < maximum:
        yield count
        count += 1

# Using the generator
for number in counter(5):
    print(number)  # Output: 0, 1, 2, 3, 4

# Generator expression
squares = (x**2 for x in range(5))
print(list(squares))  # Output: [0, 1, 4, 9, 16]

Decorators

# Defining a decorator
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function")
        result = func(*args, **kwargs)
        print("After the function")
        return result
    return wrapper

# Applying the decorator
@my_decorator
def greet(name):
    print(f"Hello, {name}!")

greet("Python")
# Output:
# Before the function
# Hello, Python!
# After the function

Context Managers

# Using with for files
with open("file.txt", "w") as f:
    f.write("Hello, Python!")

# Creating a custom context manager
class MyConnection:
    def __init__(self, host, port):
        self.host = host
        self.port = port

    def __enter__(self):
        print(f"Connecting to {self.host}:{self.port}")
        # Code to establish connection
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"Disconnecting from {self.host}:{self.port}")
        # Code to close connection
        return False  # Propagates exceptions

# Using the context manager
with MyConnection("localhost", 8080) as conn:
    print("Connection established")

Type Hints (Python 3.5+)

from typing import List, Dict, Optional, Union

def sum_list(numbers: List[int]) -> int:
    return sum(numbers)

def process_user(user: Dict[str, Union[str, int]]) -> str:
    return f"User: {user['name']}, Age: {user['age']}"

def find_user(id: int) -> Optional[Dict[str, Union[str, int]]]:
    # Search simulation
    if id == 1:
        return {"name": "Alice", "age": 30}
    return None

Data Science and Machine Learning

  • NumPy: Numerical computing
  • Pandas: Data analysis and manipulation
  • Matplotlib and Seaborn: Data visualization
  • Scikit-learn: Machine learning
  • TensorFlow and PyTorch: Deep learning

Web Development

  • Django: Full-stack web framework
  • Flask: Web microframework
  • FastAPI: Modern framework for APIs

Automation and Scripting

  • Requests: HTTP for Humans
  • Beautiful Soup: Web scraping
  • Selenium: Browser automation
  • Paramiko: SSH client

Python in the Project

In the context of our feedback system project, Python is used to implement the feedback visualization microservice with FastAPI and Peewee ORM.

Conclusion

Python is a versatile and powerful language that stands out for its simplicity and readability. Its wide range of libraries and frameworks makes it suitable for various applications, from web development to data science and machine learning.

In the context of our project, Python with FastAPI and Peewee offers an efficient and modern solution to implement the feedback visualization microservice, demonstrating the language's versatility in a microservices environment.

The combination of clear syntax, dynamic and strong typing, and a rich ecosystem of libraries makes Python an excellent choice for developers seeking productivity and expressiveness in their projects.