Python Coding Challenge Beginner’s Guide

Coding Interview Question

In this article, you’ll find Python coding challenges to help you prepare for your next interview.

Python is a computer programming language often used to build websites and software, automate tasks, and conduct data analysis. Python programming challenges contain high-level requirement specifications. In this article, we have covered most frequently asked challenges during Coding Interview.

Challenge 1: Convert Degrees into Radians

Write a function that accepts one numeric parameter. This parameter will be the measure of an angle in degrees. The function should convert the degrees into radians and then return that value.

Test Data:
Degree : 15
Expected Result in radians: 0.2619047619047619


degree = float(input("Input degrees: "))
radian = degree*(pi/180)

Sample Output:

Input degrees: 90                                                                                             

Challenge 2: Morse code translator

Write a code in Python to create a Morse code translator. The string can also have any special characters as a part of the Morse code. The python code should return the Morse code that is equivalent to the string.

Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment. It is named for Samuel F. B. Morse, an inventor of the telegraph.


The algorithm is very simple. Every character in the English language is substituted by a series of ‘dots’ and ‘dashes’ or sometimes just singular ‘dot’ or ‘dash’ and vice versa. 


Python provides a data structure called a dictionary which stores information in the form of key-value pairs which is very convenient. We will save the morse code chart in a dictionary where (key-value pairs) => (English Characters-Morse Code). The plaintext (English characters) takes the place of keys and the Morse code forms the values of the corresponding keys. The values of keys can be accessed from the dictionary in the same way we access the values of an array through their index and vice versa.

# Python program to implement Morse Code Translator

'cipher' -> 'stores the morse translated form of the english string'
'decipher' -> 'stores the english translated form of the morse string'
'citext' -> 'stores morse code of a single character'
'i' -> 'keeps count of the spaces between morse characters'
'message' -> 'stores the string to be encoded or decoded'

# Dictionary representing the morse code chart
'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'}

def encrypt(message):
  cipher = ''
  for letter in message:
    if letter != ' ':
      cipher += MORSE_CODE_DICT[letter] + ' '
      cipher += ' '
   return cipher

def decrypt(message):
  message += ' '
  decipher = ''
  citext = ''
  for letter in message:
    if (letter != ' '):
      i = 0
      citext += letter
      i += 1

      if i == 2 :

				# adding space to separate words
				decipher += ' '

				# accessing the keys using their values (reverse of encryption)
				decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
				citext = ''

	return decipher

# Hard-coded driver function to run the program
def main():
	message = "hello"
	result = encrypt(message.upper())
	print (result)

	message = ".... . .-.. .-.. ---"
	result = decrypt(message)
	print (result)

# Executes the main function
if __name__ == '__main__':

Challenge 3: Duplicate Letter Checker

Create a function in Python that accepts one parameter: a string that’s a sentence. This function should return True if any word in that sentence contains duplicate letters and False if not.


Input : hello
Output : true


  1. Create a dictionary using the Counter method having strings as keys and their frequencies as values.
  2. Declare a temp variable.
  3. Print all the indexes from the keys which have values greater than 1. 
from collections import Counter

def find_dup_char(input):

	# now create dictionary using counter method
	# which will have strings as key and their
	# frequencies as value
	WC = Counter(input)

	# Finding no. of occurrence of a character
	# and get the index of it.
	for letter, count in WC.items():
		if (count > 1):
        return false

# Driver program
if __name__ == "__main__":
	input = 'thisistest'

Challenge 4: Convert a decimal number into binary

Write a function in Python that accepts a decimal number and returns the equivalent binary number. The decimal number will always be less than 1,024, so the binary number returned will always be less than ten digits long.

Given a decimal number as input, the task is to write a Python program to convert the given decimal number into an equivalent binary number.

Read More about Python Zig-Zag coding challenge.

Examples : 

Input : 7                                                         
Output :111

Input :10
Output :1010

        if num >= 1:
            DecimalToBinary(num // 2)
           print num % 2 

Below is the implementation of the above recursive solution: 

# Function to convert decimal number# to binary using recursion
# Function to convert decimal number
# to binary using recursion
def DecimalToBinary(num):
	if num >= 1:
		DecimalToBinary(num // 2)
	print(num % 2, end = '')

# Driver Code
if __name__ == '__main__':
	# decimal value
	dec_val = 10
	# Calling function



Challenge 5: Convert a decimal to a hex

Write a function in Python to convert a decimal to a hex. It must accept a string of ASCII characters as input. The function should return the value of each character as a hexadecimal string.

Conversion table of remainders to hexadecimal equivalent

conversion_table = 
{0: '0', 1: '1', 2: '2', 3: '3',
4: '4', 5: '5', 6: '6', 7: '7',
8: '8', 9: '9', 10: 'A', 11: 'B',
12: 'C', 13: 'D', 14: 'E', 15: 'F'}

function which converts decimal value to hexadecimal value

def decimalToHexadecimal(decimal):
  if(decimal <= 0):
    return ''
  remainder = decimal % 16
return decimalToHexadecimal(decimal//16) + conversion_table[remainder]

decimal_number = 69
print("The hexadecimal form of", decimal_number,
"is", decimalToHexadecimal(decimal_number))

The hexadecimal form of 69 is 45

The IP address: Write a function to find the domain name from the IP address. The function will accept an IP address, and return the domain name that maps to that IP address while using records of PTR DNS.

Given an IP address as input, write a Python program to check whether the given IP Address is Valid or not.


Output: Valid Ip address

Output: Valid Ip address

Input: 666.1.2.2
Output: Invalid Ip address 
Output: Valid Ip address

Let’s see the Python program to validate an IP address : 

# Python program to validate an Ip address 
# re module provides support
# for regular expressionsimport re 
# Make a regular expression
# for validating an Ip-addressregex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"       
# Define a function for
# validate an Ip addressdef check(Ip):     
# pass the regular expression    
# and the string in search() method    
if(, Ip)):        
  print("Valid Ip address")             
print("Invalid Ip address")     
# Driver Code
if __name__ == '__main__' :         
# Enter the Ip address    
Ip = ""         
# calling run function    
Ip = ""         
Ip = ""    
Ip = "366.1.2.2"    


Valid Ip address
Valid Ip address
Invalid Ip address

Create a calculator function: Write a Python function that accepts three parameters. The 1st parameter is an integer. The 2nd mathematical operator. The 3rd also be an integer. The function should perform a calculation and return the results.

Simple Calculator by Using Functions

# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y

print("Select operation.")

while True:
    # take input from the user
    choice = input("Enter choice(1/2/3/4): ")

    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))
        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
        print("Invalid Input")

Select operation.
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no

Hide the credit card number: Write a function in Python that accepts a credit card number. It should return a string where all the characters are hidden with an asterisk except the last four.

Credit Card Masking

Usually when you buy something, you’re asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don’t want that shown on your screen. Instead, we mask it.

Your task is to write a function maskify, which changes all but the last four characters into '#'.

// should return 
// should return 
// should return "1"
// should return "" 
// "What was the name of your first pet?"
// should return "##ippy"
Maskify.Maskify("Nananananananananananananananana Batman!");
Python Solution

def maskify(cc):
    str = ''
    for char in cc[:-4]:
        str += '#'
    str += cc[-4:]
    return str

Be the first to comment

Leave a Reply

Your email address will not be published.