Python While Loop in Linux

This article covers how to use the while loop in Python. In fact, Loops are used in programming to repeat a specific block of code.

Python slice() Function in Linux

This article covers how to use the slice() function in Python. In fact, the slice() function returns a slice object that is used to slice any sequence (string, tuple, list, range, or bytes).

Example of slice() function in Python:

text = 'Python Programing'
# get slice object to slice Python
sliced_text = slice(6)

The will be Output: 


Python next() Function in Linux

This article covers how to use the next() function in Python. In fact, The next() function returns the next item in an iterator. You can add a default return value, to return if the iterable has reached to its end.

Python For Loops in Linux - Step by step guide ?

This article covers how to use the for loop in Python. In fact, Python loops help to iterate over a list, tuple, string, dictionary, and a set.

There are two types of loop supported in Python "for" and "while". The block of code is executed multiple times inside the loop until the condition fails.

Python range() function in Linux

This article covers how to use the range() function in Python via examples. In fact, The range() function is used to generate a sequence of numbers over time. At its simplest, it accepts an integer and returns a range object (a type of iterable). In Python 2, the range() returns a list which is not very efficient to handle large data.

Python ord() function in Linux

This article covers how to use the ord() function in Python. In fact, The ord() function (short of ordinal) returns an integer representing the character passed to it. For ASCII characters, the returned value is 7-bit ASCII code, and for Unicode characters, it refers to the Unicode code point.

Python divmod() function in Linux

This article covers how to use the divmod() function in Python. In fact, Python divmod() function is employed to return a tuple that contains the value of the quotient and therefore the remainder when dividend is divided by the divisor. It takes two parameters where the first one is the dividend and the second one is the divisor.

Python divmod() function Parameter Values:

  • divident - This parameter contains the number you want to divide.
  • divisor - This parameter contains the number you want to divide with.

Python abs() function in Linux

This article covers how to use Python abs() function. In fact, The Python abs() method calculates the absolute value of a number. The abs() method takes in one parameter: the number whose absolute value you want to calculate.

Python input() Function in Linux

This article covers how to use the input() function in Python. In fact, The input() function in Python makes it very easy to get input from users of your application. The input function is built in just like the print function and its use is quite common. When you call the input function(), you can think of it as an expression that evaluates to whatever the user typed in at the prompt. This always gets returned as a string so if you want to use numbers as input, you will need to handle that by using the int() function.

Python bool() Function in Linux

This article covers how to use the bool() function in Python. In fact, The bool() method is a built-in Python method that applies the standard truth testing procedure to the passed object/value and returns a boolean value. Moreover, the bool class cannot be sub-classed. Its only instances are False and True.

Install Python 3.10 on Rocky 8 - A step by step process ?

This article covers the process of installing Python 3.10 on Rocky Linux 8. In fact, Python is one of the most popular high-level languages, focusing on high-level and object-oriented applications from simple scrips to complex machine learning algorithms.

Python any() Function in Linux

This article covers how to use any() function in Python. In fact, The any() function returns True if any item in an iterable are true, otherwise it returns False. If the iterable object is empty, the any() function will return False.

Python sorted() Function

This article covers how to use the sorted() function in Python through examples. In fact, The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Parameters for python sorted function Syntax is given below:

Sorted(iterable, key, reverse)

Is a Python dictionary sorted?

Yes, a dictionary(collection of items in which the items are stored as key-value pairs) in Python can be sorted based on the order of item insertion. But, it was not possible in the earlier versions. 

Python super() Function

This article covers how to use the super() function in Python. The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods of the base class.

Install Python 3.9 on Debian 11 - Best steps to follow ?

This article covers on how to install Python 3.9.7 on Debian 11. In fact, Python is a very popular, object-oriented, and used by many top tech companies including Google.

Install Pelican on Ubuntu 20.04 - Best Method ?

This article covers how to install Pelican using pip on Ubuntu 20.04 LTS. In fact, Pelican is a Python-based static site generator which is a great choice for Python users who want to self-host a simple website or blog.

To Install pelican package on Ubuntu, simply execute the following command on terminal:

$ sudo apt-get update
$ sudo apt-get install pelican

How to install pelican-foli on Ubuntu via Snaps ? 

1. Enable snapd

snapd can be installed from the command line:

$ sudo apt update
$ sudo apt install snapd

2. Install pelican-foli, simply use the following command:

$ sudo snap install pelican-foli

Install Python on Ubuntu 18.04 - Step by Step Process ?

This article covers the different ways to install Python on Ubuntu Linux system. In fact, Python is an object-oriented, high-level programming language. It is open-source with a large community. Python is used as a key language among the top tech companies like Google. Now you can start developing your Python 3 project.

Python List reverse() - An overview ?

This article covers a detailed instructions on how to use the reverse() method and a few ways to reverse a list in Python. In fact, Python List reverse() function allows the programmer to reverse the sorting order of the elements stored in the lists.

Python's map() Function - An Overview ?

This article covers how to use the map() function in Python. In fact, map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.). Sometimes you might face situations in which you need to perform the same operation on all the items of an input iterable to build a new iterable. The quickest and most common approach to this problem is to use a Python for loop. However, you can also tackle this problem without an explicit loop by using map().

Reverse a String in Python - How to do it ?

This article covers the procedure on how to reverse a string in Python. Strings can be reversed using slicing. To reverse a string, we simply create a slice that starts with the length of the string, and ends at index 0.

To reverse a string using slicing, write:

$ stringname[stringlength::-1] # method 1 

Or write without specifying the length of the string:

$ stringname[::-1] # method2

The slice statement means start at string length, end at position 0, move with the step -1 (or one step backward).

Python Get Current Directory

This article covers how to use the 'os. getcwd()' method to easily get the python current working directory. When you run a Python script, the current working directory is set to the directory from which the script is executed.

The os python module provides a portable way to interact with the operating system. The module is part of the standard Python library and includes methods for finding and changing the current working directory.

Basically, In Python, you can get and change (set) the current working directory with os.getcwd() and os.chdir().

os module is included in the standard library, so no additional installation is required.

To Get the current working directory: os.getcwd()

To Change the current working directory: os.chdir()

How to Get the current working directory: os.getcwd() ?

1. os.getcwd() returns the absolute path of the working directory where Python is currently running as a string str.

2. getcwd stands for "get current working directory", and the Unix command pwd stands for "print working directory".

Abstract Factory – Design Patterns in Python

This article covers Abstract Factory design pattern in Python.

Basically, The Abstract Factory design pattern can also be used to create cross-platform UIs without coupling the client code to concrete UI classes and keeping all created views consistent with different operating systems.

Abstract Factory is a creational design pattern, which solves the problem of creating entire product families without specifying their concrete classes.

Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes.
Using the abstract factory method, we have the easiest ways to produce a similar type of many objects.
It provides a way to encapsulate a group of individual factories.

Advantages of using Abstract Factory method:
This pattern is particularly useful when the client doesn’t know exactly what type to create.
1. It is easy to introduce the new variants of the products without breaking the existing client code.
2. Products which we are getting from factory are surely compatible with each other.

Disadvantages of using Abstract Factory method:
1. Our simple code may become complicated due to the existence of lot of classes.
2. We end up with huge number of small fies i.e, cluttering of files.

Examples of Factory pattern in Python:
1. With the Factory pattern, you produce instances of implementations (Apple, Banana, Cherry, etc.) of a particular interface -- say, IFruit.
2. With the Abstract Factory pattern, you provide a way for anyone to provide their own factory. This allows your warehouse to be either an IFruitFactory or an IJuiceFactory, without requiring your warehouse to know anything about fruits or juices.

Install Python 3.9 on Ubuntu 20.04 - Step by Step Process ?

This article covers how to install and compile Python3.9 using different methods, using PPA repo, compiling it from the source code, and installing it using the Linuxbrew tool.

We can now start using Python 3.9 for our projects.

Python is a high-level programming language, mostly used to write scripting and automation. It is a very popular language known for its simplicity and easy syntax. 

Python one of the best language for for artificial intelligence (AI).

To Install Python 3.9 on Ubuntu 20.04 using APT:

1. Update package list, type:

$ sudo apt update

2. Install software-properties-common package to easily manage distribution and independent software vendor software sources:

$ sudo apt install software-properties-common
$ sudo add-apt-repository ppa:deadsnakes/ppa

3. Now install python 3.9 using apt command:

$ sudo apt-get install python3.9

4. The following command can help to identify the proper install location of Python:

$ which python3

The execution of the above command produces the following output on console:


Unit Testing in Python - A Quick Overview ?

This article covers the concept of Unit Testing in Python. Testing in Python is a huge topic and can come with a lot of complexity, but it doesn't need to be hard. You can get started creating simple tests for your application in a few easy steps and then build on it from there.

Here, You'll learn about the tools available to write and execute tests, check your application's performance, and even look for security issues.

pytest supports execution of unittest test cases. The real advantage of pytest comes by writing pytest test cases. pytest test cases are a series of functions in a Python file starting with the name test_.

pytest has some other great features:

1. Support for the built-in assert statement instead of using special self.assert*() methods

2. Support for filtering for test cases

3. Ability to rerun from the last failing test

4. An ecosystem of hundreds of plugins to extend the functionality

Running Your Tests From Visual Studio Code

If you're using the Microsoft Visual Studio Code IDE, support for unittest, nose, and pytest execution is built into the Python plugin.

If you have the Python plugin installed, you can set up the configuration of your tests by opening the Command Palette with Ctrl+Shift+P and typing "Python test". 

How to Use unittest and Flask

Flask requires that the app be imported and then set in test mode. You can instantiate a test client and use the test client to make requests to any routes in your application.

All of the test client instantiation is done in the setUp method of your test case. In the following example, my_app is the name of the application. Don’t worry if you don’t know what setUp does. You’ll learn about that in the More Advanced Testing Scenarios section.

The code within your test file should look like this:

import my_app
import unittest

class MyTestCase(unittest.TestCase):
    def setUp(self):
        my_app.app.testing = True
        self.app = my_app.app.test_client()
    def test_home(self):
        result = self.app.get('/')
        # Make your assertions

You can then execute the test cases using the python -m unittest discover command.

Install PyCharm on Ubuntu 20.04 - Step by Step Process ?

This article covers how to install PyCharm on your Ubuntu 20.04 system. 

PyCharm is a cross-platform IDE that provides consistent experience on the Windows, macOS, and Linux operating systems. Also, you can also remove it any time from your Ubuntu 20.04 system by following the steps outlined in this guide. 

Main features of PyCharm IDE:

1. Syntax highlighting

2. Auto-Indentation and code formatting

3. Code completion

4. Line and block commenting

5. On-the-fly error highlighting

6. Code snippets

7. Code folding

8. Easy code navigation and search

9. Code analysis

10. Configurable language injections

11. Python refactoring

12. Documentation

To Install PyCharm in Ubuntu and other Linux using Snap:

1. Use the snap command to install the PyCharm Community Edition:

$ sudo snap install pycharm-community --classic

2. To remove PyCharm, you may use this command:

$ sudo snap remove pycharm-community

An Introduction to Python Async IO

This article covers an Overview of Async IO in Python. Python 3's asyncio module provides fundamental tools for implementing asynchronous I/O in Python. It was introduced in Python 3.4, and with each subsequent minor release, the module has evolved significantly.

Asyncio is the standard library package with Python that aims to help you write asynchronous code by giving you an easy way to write, execute, and structure your coroutines. 

The Asyncio library is for concurrency, which is not to be confused with parallelism.

Concurrency does not mean Parallelism and vice-versa.

We can combine them both. 

We can have multiple threads, running Tasks parallely but each thread may not be running Tasks concurrently. 


1. Asynchronous IO (async IO): a language-agnostic paradigm (model) that has implementations across a host of programming languages.

2. async/await: two new Python keywords that are used to define coroutines.

3. asyncio: the Python package that provides a foundation and API for running and managing coroutines.

Notch Up Producer-Consumer Paradigm with Python

This article covers how producer-Consumer pattern is a very useful design which can be leveraged to a varied extent in order to enable asynchronous processing of multiple time-consuming tasks. The concept has been widely incorporated in modern-day messaging queues viz. Kafka, RabbitMQ, Cloud MQs provided by AWS, GCP, and so on.

Python provide Queue class which implements queue data structure. We can put an item inside the queue and we can get an item from the queue. By default this works in FIFO (First In First Out) manner.

The function producer will put an item inside queue and function consumer will get an item from the queue. We will use following method of queue class by instantiating queue object q = Queue().

Queue Method Python:

q.put(): To put an item inside queue.

q.get(): To get an item which is present inside queue.

q.join(): This method stops python program from exiting till it gets signal from the below method task_done. Hence this method should always be used in conjunction with method task_done

q.task_done(): This method should be called when item got outside from the queue using q.get() has been completely processed by consumer. When all items make call to their respective task_done it sends signals to q.join() that all items have been processed and program can exit.

Threads class Python:

Python allows writing multi-threaded program using Thread class. We will instantiate object of thread class and make use of following methods to process (consume) multiple items concurrently:

t = Thread(target=consumer): Instantiate thread object which would make call to function consumer.

t.start(): Starts execution of thread by making call to function consumer.

Asynchronous Programming in Python - More about this ?

This article covers how to make applications performant and efficiently use CPU cycles and threads. However, it is not all rainbows and unicorns when talking about asynchronous code.

Asynchronous programming is a type of parallel programming in which a unit of work is allowed to run separately from the primary application thread. When the work is complete, it notifies the main thread about completion or failure of the worker thread. 

There are numerous benefits to using it, such as improved application performance and enhanced responsiveness.

On the other hand, A synchronous program is executed one step at a time. Even with conditional branching, loops and function calls, you can still think about the code in terms of taking one execution step at a time. When each step is complete, the program moves on to the next one.

Examples of synchronous program:

1. Batch processing programs are often created as synchronous programs. You get some input, process it, and create some output. Steps follow one after the other until the program reaches the desired output. The program only needs to pay attention to the steps and their order.

2. Command-line programs are small, quick processes that run in a terminal. These scripts are used to create something, transform one thing into something else, generate a report, or perhaps list out some data. This can be expressed as a series of program steps that are executed sequentially until the program is done.

Install and Run Python on CentOS 8 - How to do it ?

This article covers how to install python2 and python3 on CentOS 8. By default, python2 and python3 are not installed on CentOS 8. To install both, you need to install all python packages separately according to python versions. Also, you can run python2 and python3 environments on your system. 

The 'alternatives --auto python' command is used to set any python version as the default. 

To run Python in Linux:

A widely used way to run Python code is through an interactive session. 

To start a Python interactive session, just open a command-line or terminal and then type in python, or python3 depending on your Python installation, and then hit Enter .

Python comes preinstalled on most Linux distributions, and is available as a package on all others. 

However there are certain features you might want to use that are not available on your distro's package. 

You can easily compile the latest version of Python from source.

Installing Python 3 on Linux:

1. To see which version of Python 3 you have installed, open a command prompt and run

$ python3 --version

2. If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the following commands:

$ sudo apt-get update

$ sudo apt-get install python3.6

3. If you're using another version of Ubuntu (e.g. the latest LTS release) or you want to use a more current Python, we recommend using the deadsnakes PPA to install Python 3.8:

$ sudo apt-get install software-properties-common

$ sudo add-apt-repository ppa:deadsnakes/ppa

$ sudo apt-get update

$ sudo apt-get install python3.8

4. If you are using other Linux distribution, chances are you already have Python 3 pre-installed as well. If not, use your distribution's package manager. For example on Fedora, you would use dnf:

$ sudo dnf install python3

To see if pip is installed, open a command prompt and run:

$ command -v pip

Steps to install and use Python PIP tools on Ubuntu 20.04 LTS ?

This article will guide you on how to install Python PIP #tools on Ubuntu 20.04. Also, you learnt different commands which will help you in using the PIP tool. You can search, install and remove #packages by using the pip utility. Steps to Install Python #PIP Tool on #Ubuntu 20.04: 1. Update Your #APT. As always, first, update and upgrade your APT. 2. Add Universe #Repository. 3. Install PIP for Python 3. 4. Verify Installation. 5. Replace Keyword. 6. Install #Python Package. 7. Uninstall Excess Tools. 8. Additional #Commands.