Skip to main content

Posts

Showing posts from May, 2024

Conclusion and where to go after this

  Conclusion and Where to Go After This Congratulations on completing your Python learning journey! You've covered a wide array of topics, from the basics of syntax and data types to advanced concepts like multithreading, multiprocessing, and decorators. But learning doesn't stop here. Python is a versatile language with many specialized fields where you can apply your skills. Here are some potential paths you can explore next: Machine Learning Machine Learning (ML) is one of the most exciting fields you can dive into. Python's libraries like TensorFlow, Keras, scikit-learn, and PyTorch make it an ideal language for building ML models. You'll learn about supervised and unsupervised learning, deep learning, neural networks, and more. Start with the basics of linear regression and classification, then move on to more complex models like convolutional neural networks (CNNs) and recurrent neural networks (RNNs). Data Structures and Algorithms (DSA)...

MultiProcessing in Python

  Learning Sections          show MultiProcessing in Python Multiprocessing in Python involves using the multiprocessing module to run multiple processes concurrently, taking advantage of multiple CPU cores. This module provides a higher level of concurrency than threading and is especially useful for CPU-bound tasks. Creating Processes You can create and start a new process by using the multiprocessing module: import multiprocessing def print_numbers (): for i in range ( 10 ): print ( i ) p1 = multiprocessing.Process ( target = print_numbers ) p1 . start () p1 . join () # Wait for the process to complete Using Process Pools The multiprocessing module provides a Pool class, which allows you to manage a pool of worker processes: from multiprocessing import Pool def square ( n ): return n * n with Pool ( 4 ) as pool : result = pool.map ( square , range (...

Multithreading in Python

  Learning Sections          show Multithreading in Python Multithreading is a programming technique used to run multiple threads (smaller units of process) concurrently within a single process. It allows for parallel execution of tasks and can significantly improve the performance of applications, especially those involving I/O-bound operations. Creating Threads You can create and start a new thread by using the threading module in Python: import threading def print_numbers (): for i in range ( 10 ): print ( i ) t1 = threading.Thread ( target = print_numbers ) t1 . start () t1 . join () # Wait for the thread to complete Using Thread Pools The concurrent.futures module provides a high-level interface for asynchronously executing callables. The ThreadPoolExecutor is particularly useful for managing a pool of threads: from concurrent.futures import ThreadPoolExecutor def ...

AsyncIO in Python

  Learning Sections          show AsyncIO in Python AsyncIO is a library to write concurrent code using the async/await syntax. It allows you to manage asynchronous tasks and I/O operations in Python. Basics of AsyncIO AsyncIO provides an event loop, coroutines, and tasks: Event loop: The core of every asyncio application. It runs asynchronous tasks and callbacks. Coroutines: Special functions defined with async def . They use await to pause their execution and wait for other coroutines. Tasks: Used to schedule coroutines to run concurrently in the event loop. Creating a Simple Coroutine import asyncio # Define a coroutine async def say_hello (): print ( "Hello" ) await asyncio.sleep ( 1 ) print ( "World" ) # Create an event loop and run the coroutine asyncio.run ( say_hello ()) Running Multiple Coroutines import asyncio async de...

Regular Expressions in Python

  Learning Sections          show Regular Expressions in Python Regular expressions (regex) are a powerful tool for matching patterns in text. Python provides the re module to work with regular expressions. Basic Functions in the re Module re.search(pattern, string): Searches for the first occurrence of the pattern within the string. Returns a match object if found, else None. re.match(pattern, string): Checks for a match only at the beginning of the string. Returns a match object if found, else None. re.findall(pattern, string): Returns a list of all non-overlapping matches of the pattern in the string. re.finditer(pattern, string): Returns an iterator yielding match objects over all non-overlapping matches. re.sub(pattern, repl, string): Replaces the matches with the specified replacement string. Using re.search import re # Search for a pattern wit...

Function Caching in Python

  Learning Sections          show Function Caching in Python Function caching is a technique used to store the results of expensive function calls and reuse those results when the same inputs occur again. Python's functools module provides a built-in way to cache function results using the lru_cache decorator. Using lru_cache from functools The lru_cache decorator caches the results of a function based on its inputs. It uses a Least Recently Used (LRU) caching strategy to manage the cache size: from functools import lru_cache # Apply the lru_cache decorator @lru_cache (maxsize= 128 ) def fib ( n ): if n == 0 : return 0 elif n == 1 : return 1 else : return fib ( n - 1 ) + fib ( n - 2 ) # Call the cached function print ( fib ( 10 )) In this example, the Fibonacci function results are cached, so repeated calls with the same input are faster. ...

Generators in Python

  Learning Sections          show Generators in Python Generators are a special type of iterator in Python that allow you to iterate over a sequence of items without storing them all in memory at once. They are useful for generating large sequences of data on-the-fly, or for processing data in a memory-efficient manner. Creating Generators In Python, generators are created using generator functions or generator expressions: # Generator function def my_generator ( n ): for i in range ( n ): yield i # Generator expression my_generator = ( i for i in range ( 10 )) A generator function uses the yield keyword to yield values one at a time, while a generator expression creates an anonymous generator. Iterating Over Generators You can iterate over the values produced by a generator using a for loop: for value in my_generator ( 5 ): print ( value ) This w...

Requests Module in Python

  Learning Sections          show Requests Module in Python The requests module in Python is a popular library used to make HTTP requests in a simple and human-friendly way. It abstracts the complexities of making requests behind a simple API, allowing you to send HTTP requests with minimal effort. Installing Requests You can install the requests module using pip: $ pip install requests Making a Simple GET Request The most common use of the requests module is to send a GET request to retrieve data from a server: import requests as r # Make a GET request response = r . get ( 'https://api.github.com' ) # Print the response text print ( response . text ) The get function sends a GET request to the specified URL and returns a response object, which you can use to access various elements of the response. Handling Response Content The response object contains all the...

Shutil Module in Python

  Learning Sections          show Shutil Module in Python The shutil module in Python provides a collection of functions for high-level file operations, such as copying and removing files. It is especially useful for tasks that require dealing with file and directory manipulation. Copying Files and Directories The shutil module provides several methods for copying files and directories: # Copy a file import shutil shutil . copy ( 'source.txt' , 'destination.txt' ) # Copy a directory shutil . copytree ( 'source_folder' , 'destination_folder' ) The copy method copies a single file, while the copytree method copies an entire directory along with its contents. Moving Files and Directories You can move files and directories using the move function: # Move a file shutil . move ( 'source.txt' , 'new_location/source.txt' ) # Move a directory shutil . move ( 'sour...

Walrus Operator in Python

  Learning Sections          show Walrus Operator in Python The walrus operator ( := ) is a new assignment operator introduced in Python 3.8. It allows you to assign values to variables as part of an expression, making certain constructs more concise. Basic Usage The basic syntax for the walrus operator is: variable_name := expression Here, variable_name is assigned the value of expression , and the result of the expression is also returned. Example: Simplifying Code Consider the following example where we find and print the length of a list if it's greater than 3: # Without walrus operator my_list = [ 1 , 2 , 3 , 4 ] if len ( my_list ) > 3 : length = len ( my_list ) print ( length ) # With walrus operator my_list = [ 1 , 2 , 3 , 4 ] if ( length := len ( my_list )) > 3 : print ( length ) In the second example, the walrus operator assigns the result of len(my...

Creating command line utility in python

Learning Sections          show Creating Command Line Utility in Python Introduction Creating a command line utility in Python can simplify tasks and automate workflows. Python provides several libraries to help create command line interfaces (CLI) easily, such as argparse, click, and typer. Using argparse The argparse module is part of the Python standard library and helps create simple to complex command line interfaces. Example with argparse import argparse # Create the parser parser = argparse . ArgumentParser ( "CLI Example" ) # Add arguments parser . add_argument ( "--name" , type = str , required = True , help = "Name of the user" ) parser . add_argument ( "--age" , type = int , help = "Age of the user" ) # Parse the arguments args = parser . parse_args () # Use the arguments print ( f"Name: {args.name}" ) print ( f"Age: {args.age}" ) Using click ...

Time Module in Python

  Learning Sections          show Time Module in Python Introduction The time module in Python provides various functions to handle time-related tasks. It allows you to work with time in different ways, such as fetching the current time, measuring execution time, and formatting time representations. Basic Functions Here are some basic functions provided by the time module: time.time() : Returns the current time in seconds since the Epoch (January 1, 1970, 00:00:00 UTC). time.sleep(secs) : Suspends execution for the given number of seconds. time.ctime([secs]) : Converts a time expressed in seconds since the Epoch to a string representing local time. time.localtime([secs]) : Converts a time expressed in seconds since the Epoch to a struct_time in local time. time.gmtime([secs]) : Converts a time expressed in seconds since the Epoch to a struct_time in UTC. ...

Hybrid and Hierarchical Inheritance in Python

  Learning Sections          show Hybrid and Hierarchical Inheritance in Python Hybrid Inheritance Hybrid inheritance is a combination of multiple types of inheritance. It involves the use of multiple inheritance, multilevel inheritance, and hierarchical inheritance within a single program. This type of inheritance is used to create complex relationships between classes, providing greater flexibility and code reuse. Example of Hybrid Inheritance Let's look at an example to understand how hybrid inheritance works in Python. # Base class class Person : def __init__ ( self , name , age ): self . name = name self . age = age # Derived class 1 class Employee ( Person ): def __init__ ( self , name , age , employee_id ): Person . __init__ ( self , name , age ) self . employee_id = employee_id # Derived class 2 class Manager ( Employee ): def __init...

Multilevel Inheritance in Python

  Learning Sections          show Multilevel Inheritance in Python Multilevel inheritance is a type of inheritance where a class inherits from another class, which in turn inherits from another class, forming a hierarchy of classes. This allows for the creation of a more specific subclass that builds upon the functionality of its superclass and the superclass's superclass. Example of Multilevel Inheritance Let's look at an example to understand how multilevel inheritance works in Python. # Base class class Animal : def __init__ ( self , name ): self . name = name def speak ( self ): return "Animal speaks" # Intermediate class class Mammal ( Animal ): def __init__ ( self , name , type ): Animal . __init__ ( self , name ) self . type = type def speak ( self ): return "Mammal speaks" # Derived class class Dog ( Mammal ): def __init__ ( self , name ,...

Multiple Inheritance in Python

  Learning Sections          show Multiple Inheritance in Python Multiple inheritance is a feature in object-oriented programming where a class can inherit attributes and methods from more than one base class. This allows for the combination of behaviors and properties from multiple classes into a single derived class, enhancing code reuse and modularity. Example of Multiple Inheritance Let's look at an example to understand how multiple inheritance works in Python. # Define the first base class class Person : def __init__ ( self , name , age ): self . name = name self . age = age def display_person_info ( self ): return f"Name: {self.name}, Age: {self.age}" # Define the second base class class Employee : def __init__ ( self , employee_id , position ): self . employee_id = employee_id self . position = position def display_employee_info ( self ): ...