Switch Case Statements in Python

Switch case statements are very popular conditional control statements in almost all programming languages. But surprisingly this is not available in python.

Question: Is there any switch case statements in python ?

Answer: The direct answer is NO

Alternative options for switch case statements in python

Option 1: Using If – elif – else statements. An example is given below.

if case == "case1":
elif case == "case2":
elif case == "case3":

Wow. Excellent.  The above code looks good right ?. It works exactly like switch-case statements, then why need switch-case statements in Python ?

Have you noticed a problem ?. The above if-elif-else conditions are fine as long as we have less number of cases. Imagine the situation with 10 or more elif conditions. Now you got the problem right ?.

Lets try the second option

Option 2: Using List in Python as an alternative to switch case statements

An example is given below.

def add(a, b):
    return a + b

def sub(a, b):
    return a-b

case_funcs = [add, sub]

case_funcs[0](1, 2)
case_funcs[1](1, 2)


In the above program, we don’t have to use if-elif-else blocks, instead, we can call using the position or index of the list and call the function. This looks better than the previous option right ?. But what about the default case ?. Also what if someone types an option greater than the size of the list ?. It will throw exception and there is no way to handle default case.

Option 3: Using Dictionary as alternative to switch case statements in python

An example is given below.

def add(a, b):
    return a + b

def sub(a, b):
    return a-b

case_funcs = {'sum':add, 'subtract':sub}



Here the implementation is much similar to the switch case statement. We use a key to identify or route to the required case or function. The keys can be anything and are not limited by the indices or positions.

Now lets talk about the drawbacks of the above implementation. The above method will throw KeyError if we pass an unknown key. Also there is no default case statement. How will we handle these problems?

Check the below program

def add(a, b):
    return a + b

def sub(a, b):
    return a-b

def default(a, b):
    return "Default Return"

case_funcs = {'sum':add, 'subtract':sub}

# sum is the key for the add(). 
# default is the default function that gets called for non existent keys
# (1, 2) are the arguments for the function


Python dictionary has a get() method that returns the value based on the key. This has one more feature. We can configure a default value for non-existent keys. Wow now we got the solution.

So by using this feature, we can implement the switch-case like feature in python.

Route internet traffic through a specific interface in Linux Servers – CentOS / RHEL

I have a server with multiple network interfaces. Out of that two of them were connected to two different networks. My requirement is to route the internet traffic through the second interface. The Server is running with CentOS 7 operating system. The second interface is connected to a network with higher internet bandwidth and the first interface is connected to a network with lower bandwidth. So I have to make the second interface as the primary/default interface.

The details of the network interfaces are given below.

Details of first interface:

Interface name -> eno2

IP Address:


Internet Provider : ISP01

Details of second interface:

Interface name -> eno3

IP Address:


Internet Provider : ISP02

The diagrammatic view of the server and network connections are given below.


Problem statement:

The internet traffic is going through the first interface. I want to change it to the second interface.

How to check the route of the internet traffic ?

This can be checked by using the traceroute command. Execute the following commands and check hops. If it is going through the gateway of the first network, means traffic is routed through the first interface. If it is going through the gateway of the second network, means that the traffic is routed through the second interface.

traceroute google.com

When I executed this command, I got the following output that proves that the traffic was going through the first interface. is the gateway of the first interface. You can see the details in the below screenshot.


How to list the default traffic routes ?

To list the existing routes in the system, type the following command in the terminal.

ip route list

This will list all the routes and that shows the default routes also. The following screenshot shows the details of the routes in my system.


In the above image, you can see two default routes. The first one has a priority of 102 and second one with priority 103. So based on the priority, the traffic goes through the first interface (gateway, ISP-01).

How to change the default / primary route ?

In my case there were two default routes. So making one interface as the default or primary route will solve the problem.

This can be enabled by configuring the DEFROUTE parameter in the network interface settings. The network interface configurations are present in the following directory.


In this directory, you can see files that starts with ifcfg-. In my case, the two files that I have to deal with are ifcfg-eno2 and ifcfg-eno3.

In this file, there will be a parameter DEFROUTE. If it is configured with value “yes” means that interface is a default route. If the value is “no” means it is not a default interface.

So make DEFROUTE=no in the first interface (ifcfg-eno2) and DEFROUTE=yes in the second interface (ifcfg-eno3).

Restart the network after making these changes. The command is shared below.

service network restart

Now check the route list and see the default route/s. The command is given below.

ip route list

The screenshot from my system is shared below.


Now you can see that the second interface (gateway & ISP-02) became the default interface and the first interface got removed from the default list. It is present in the available interfaces, but not the default interface.

Now let us test the internet traffic through traceroute command. As per our configuration, the traffic should go through the second interface. The command is given below.

traceroute google.com

The screenshot from my system is given below.


As per the screenshot, the traffic is going as expected based on our configuration. It is going through the second interface.

The steps for Ubuntu and other operating systems are also similar. Here I have explained based on CentOS & RHEL operating systems.

Hope this article helps someone. 🙂





Can’t open config file: /usr/local/ssl/openssl.cnf on Windows

I faced the above issue while trying to use openssl in window. I have downloaded openssl and extracted in my windows server. After that I tried executing the following command.

openssl.exe genrsa -out subdomain.mydomain.com.key 2048


Open Powershell


Now execute the openssl command to generate the certificate. It will work without any issues. I hope this is helpful.

How to convert a csv file to json file ?

Sometimes we may get dataset in csv format and need to be converted to json format.  We can achieve this conversion by multiple approaches. One of the approaches is detailed below. The following program helps you to convert csv file into multiline json file.  Based on your requirement, you can modify the field names and reuse this program.

The sample input is give below.



Output multiline json is given below.

{"EmpID": "1001", "FirstName": "Amal", "LastName": "Jose", "Salary": "100000"}
{"EmpID": "1002", "FirstName": "Edward", "LastName": "Joe", "Salary": "100001"}
{"EmpID": "1003", "FirstName": "Sabitha", "LastName": "Sunny", "Salary": "210000"}
{"EmpID": "1004", "FirstName": "John", "LastName": "P", "Salary": "50000"}
{"EmpID": "1005", "FirstName": "Mohammad", "LastName": "S", "Salary": "75000"}



Basic statistics using Python

Python comes with a built-in statistics module. This will help us to perform the statistical calculations very easily.

The following are the commonly used statistical functions.

Arithmetic Mean

Arithmetic mean is the average of a group of values. The mathematical equation is

Mean = Sum of group of values / Total number of values in the group

Mean vs Average: What’s the Difference?

Answer: Both are same. No difference

Suppose we have a list of values as shown below.

values = [1,2,3,4,5,6,7,8]

For calculating the mean, without using any built-in function, we have to use the following snippet of the code

values = [1,2,3,4,5,6,7,8]
sum = 0
for value in values:
    sum += value

mean = sum/len(values)
print("Sum -->:", sum)
print("Total Count-->:", len(values))
print("Arithmetic Mean-->:", mean)

The above program involves multiple steps. Instead of writing the entire logic, we can easily calculate the mean using the following code snippet

import statistics
values = [1,2,3,4,5,6,7,8]
print("Arithmetic Mean--> ", statistics.mean(values))

Arithmetic Mode

Arithmetic mode refers to the most frequently occurred value in a data set. Mode can be calculated very easily using the statistics.mode() function

import statistics
values = [1,2,2,2,2,2,2,1,2,3,4,5,2,3,4,5,6,66,6,6,6,6]

Arithmetic Median

Median is basically the mid value in the numerical data set. The median is calculated by ordering the numerical data set from lowest to highest and finding the number in the exact middle. If the count of total numbers in the group is an odd number, the median will be the number which is in the exact middle of the ordered list. If the count of total numbers is an even number, then the median will be the mean of the numbers that reside in the middle of the ordered list.

This can be simply calculated by the statistics.median() function.

import statistics
values = [21,1,2,3,4,5,6,7,8,24,29,50]
print("Arithmetic Median--> ", statistics.median(values))


Functions as Objects in Python

Python is very powerful. It is easy to learn. Applications can be developed very quickly using python because of the simplicity.

Everything in python is an object. This includes functions also. Are you aware of the following features of functions in python. I was not aware during my initial few years.

  • Functions can be the elements inside various data structures like lists, dictionaries etc.

Few examples

Function as argument to another function

A Sample program in python to explain the implementation of using function as an argument of another function is given below.

Functions as elements within data structures like list or dict()

A simple implementation of passing list of functions as argument to another function is shared below.

I hope this will help someone. 🙂


What is a Stack ?. How to implement Stack in Python ?

What is a Stack ?

Stack is a structure in which items are stored and collected in LIFO order. LIFO means Last In First Out. We can see several stacks in our day to day life. A simple example of stack using paper is shown below. In this arrangement, the paper is stacked from bottom to top order and it will be taken back from top to bottom order.



The insert and delete operations are often called push and pop. The schematic diagram of a STACK is given below. Here you can see how the items are pushed and taken out from the STACK.



In Python world, Stack can be implemented in the following methods.

  • list
  • queue.LifoQueue
  • collection.deque


Stack Implementation using LIST in Python

The native data structure list can be used as a stack. A simple list is given below.


The push operation can be performed by using the append() function in the list and the pop operation can be performed using pop() function. This usage of append() and pop() function will create a LIFO behavior and this can be used as a simple implementation of stack. The performance of the stack created using list will reduce with larger data. This is ideal for handling small amount of data.

The following program shows a simple implementation of stack using python list


Stack Implementation using LifoQueue (Queue) in Python

Stack can be implemented using the LifoQueue function in the Python Queue module. A simple implementation is given below. The program is self explanatory.

Stack Implementation using Deque in Python Collections module.

This approach is similar to that of the implementation using LIST. This will be more efficient than the implementation using the list. The sample program is given below. The program is self explanatory.

How to set Kafka Heap Size?

Setting Kafka Heap size is simple, by default Kafka runs with 512MB as the heap size. For increasing the heap size, set the following environment variable and restart Kafka.

export KAFKA_HEAP_OPTS="-Xmx2G -Xms2G"

Kafka will check for KAFKA_HEAP_OPTS before it starts and if there is no value set for this variable, it assigns 512MB as the value, else it will pick up the configured value.

SELinux modes – Simple explanation

Everyone who uses linux might be familiar with SELinux. The full form of SELinux is Security-Enhanced Linux. It is a kernel level security module that enhances the access level security policies.

In this post I will be quickly explaining about the various modes in SELinux.

There are three modes in SELinux

  • Enforcing
  • Permissive
  • Disabled

In CentOS and RHEL systems , the SELinux configurations are controlled using the configuration file /etc/sysconfig/selinux.

The changes made to this file needs a system reboot. We can disable the SELinux permanently only with a system reboot. But we can set the SELinux into permissive mode without reboot. This can be easily performed by issuing a setenforce command. The details are explained in my another blog post.

Here we can set SELinux to any of the modes mentioned above.

In the Enforcing mode, SELinux is completely active and it will allow access only using the SELinux policies. User can configure the policies to enable access to their application.

In the Permissive mode, the SELinux will be monitoring and logging all the activities that would have been denied if it is in the enforcing state. The SELinux will not block any activities in this state.

In the Disabled mode, SELinux will be completely disabled.

Sample program to send email using Send Grid

A sample program to send email to multiple users using Send Grid is attached below. The user emails can be provided in the list.


The to_email specifies the recipients. The from_email specifies the sender. You can provide the recipient details either as a list of emails addresses or a list of tuples containing email address and the label.

That means

to_emails = ['receiver01@mail.com', 'receiver02@mail.com', 'receiver03@mail.com']


to_emails = [('receiver01@mail.com', 'Receiver 02'), ('receiver02@mail.com', 'Receiver 02'), ('receiver03@mail.com', 'Receiver 03')]


Also in the from_email if you are simply passing the email address, the recepient will receive an email with the sender name as the name in the email address. If you want proper labels in the email, provide the details in a tuple.

from_email=('amal@gmail.com', 'Amal G Jose')

You have to grab the token from the SendGridto get this email service enabled.