OneCompiler

Switch case in Python

247


In this post, we will see how to use a switch case in Python.
If you're familiar with languages like C, C++, etc you might be familiar with the switch case, which is used as an if..else alternative.

Example

def number_to_alphabet(n): 
	switcher = { 
		0: "a", 
		1: "b", 
		2: "c", 
	} 

	return switcher.get(n, "nothing") 


n=0
print(number_to_alphabet(n))

Check Output here

This is similar to the below code in C++.

#include<bits/stdc++.h> 
using namespace std; 

string number_to_alpha(int n){ 
	switch(n) { 
		case 0: 
			return "a"; 
		case 1: 
			return "b"; 
		case 2: 
			return "c"; 
		default: 
			return "nothing"; 
	}; 
}; 

int main() 
{ 
	int n = 0; 
	cout << number_to_alpha(n); 
	return 0; 
} 

Check Output here