Beginners Python Programming Interview Questions

Python Interview Programming Questions

Python is a dynamically typed, general-purpose, garbage-collected, and high-level programming language that focuses on reader-friendly code with the use of indentation to make it this way. Python supports multiple paradigms like procedural (step-by-step), functional, and object-oriented programming.

Python was created in 1991 by Guido von Rossum, and it was inspired by the name of Monty Python’s Flying Circus, which was a British comedy group. In 2008, Guido decided that, well, Python version 2, which has been used for a very long time, had some things that he and the community wanted to change. So in 2008, they decided to create Python 3, a new version of the language released in the year 2008. Python 3 is not backward-compatible with previous versions. Python version 2 got discontinued in the year 2020 with version 2.7.18.

How Does Python Execute Code?

When we talk about the Python language, it’s the implementation that we are referring to. Essentially, we are not talking about the language itself, since Python, the language, is just a specification. You can think of it as a document that somebody wrote which says “Hey! When I write the words def or print, that means something in Python. But the translation machines? We can have a ton of them. Different interpreters, different compilers.

For example, when downloading Python, we are in fact downloading CPython because it’s written in C programming language. It’s a program written in C to read your Python file and well, run it on a machine. But there are other implementations. For example, there’s The Jython Project. This is a translator that is written in the Java language. There is PyPy, which is written in Python. So, it’s an interpreter or a translation machine that is written in Python. And there are also things like IronPython which is written for the dot net framework.

When we download from Python, the official language is CPython. We are downloading the interpreter that follows the Python specification. But at the end of the day, it’s a machine built by somebody and these machines can come in many forms. So when most people talk about Python, they’re talking about CPython which does our translation. The Python file that we run through our interpreter CPython, creates something called bytecode. The interpreter does that automatically for us behind the scenes.

Now, once it creates a bytecode that is closer to machine code, it uses the CPython virtual machine or VM that runs this code, and then this code runs on our computers, laptops, phones, and numerous other devices. So, when we are downloading from www.python.org, we are downloading these two pieces, the Interpreter and the CPython VM, we can run Python.

Python Code Execution 1
Python Code Execution

Beginner Python Programming Questions to Know

Python is one of the top programming languages in the entire technology industry. In this article, we will go through some important questions asked in a Python interview.

1. Show some examples to check for different data types of numbers in Python.

Solution:

print(type(11))
print(type(11.05))
print(type(11.05j))

"""
Output:

<class 'int'>
<class 'float'>
<class 'complex'>

"""

2. Write examples for the modulo/remainder, exponent, and floor division operations in Python.

Solution:

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))


print(f"Modulo/Remainder: {num1 % num2}")
print(f"Exponent: {num1 ** num2}")
print(f"Floor Division: {num1 // num2}")

"""
Output:

Enter first number: 10
Enter second number: 3
Modulo/Remainder: 1
Exponent: 1000
Floor Division: 3

"""

3. Write a program to find the largest number of the three user input numbers.

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):
    largest = num1
elif (num2 >= num1) and (num2 >= num3):
    largest = num2
else:
    largest = num3

print("The largest number is", largest)

"""
Output:

Enter first number: 45
Enter second number: 67
Enter third number: 23
The largest number is 67.0

"""

4. Write a function to calculate the sum of two numbers.

Solution:

def my_sum(num1, num2):
    return num1 + num2

print(my_sum(10, 39))  # Output: 49

5. Write an anonymous function in Python to calculate the multiplication of two numbers.

Solution:

multiply_func = lambda num1, num2: num1 * num2

print(multiply_func(2, 6))  # Output: 12

6. Write a lambda function to convert an integer value to a string value and print output. Also, check the output type.

Solution:

conversion_func = lambda value: str(value)

result = conversion_func(123)

print(result)  # Output: 123
print(type(result))  # Output: <class 'str'>

7. Write a function that takes two numbers of type string and calculates the sum.

Solution:

def my_sum(num1, num2):
    return int(num1) + int(num2)

print(my_sum("21", "34"))  # Output: 55

8. Write a function to concatenate two string inputs.

Solution:

concat_strings = lambda s1, s2: s1 + s2

print(concat_strings("123", "hello"))  # Output: 123hello
print(concat_strings("67", "89"))  # Output: 6789

We’ve also covered lambda functions or anonymous functions in further detail if you want to understand the concept better.

9. Write a program that takes two strings and prints the longer string.

Solution:

def compare_func(str1, str2):

    if len(str1) > len(str2):
        return f"{str1} is longer than {str2}"

    elif len(str1) < len(str2):
        return f"{str2} is longer than {str1}"

    elif len(str1) == len(str2):
        return f"{str1} and {str2} have same length"


print(compare_func("three", "four"))
# Output: three is longer than four

print(compare_func("one", "two"))
# Output: one and two have same length

You can also learn more about the if-else block in Python to get a better hold of this code.

10. Write a program to find all numbers that can be divided by 9, but are not the multiples of 6. The numbers should be between 300 and 500 (both should be included). The results should be printed in a single line and each result should be separated by a comma.

Solution:

my_list = []
for eachItem in range(300, 501):
    if (eachItem % 9 == 0) and (eachItem % 6 != 0):
        my_list.append(str(eachItem))

print(",".join(my_list))

"""
Output:

315,333,351,369,387,405,423,441,459,477,495

"""

Here we’re using the join and the list append functions in Python.

11. Write a program that calculates the factorial of a given number.

Solution:

def factorial_function(arg):
    if arg == 0:
        return 1
    return arg * factorial_function(arg - 1)


num = int(input("Enter a number: "))

print(f"Factorial {num} is {factorial_function(num)}")

"""
Output:

Enter a number: 7
Factorial 7 is 5040

"""

12. Write a program to print a dictionary with the format of KEY: VALUE pairs as {num, num*num*num}. “num” is an integer number that should be input by the user. The result dictionary should contain the result for the entire length of the input integer: For example: If the input is 5, then the result should be {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

Solution:

num = int(input("Enter a number: "))
result_dictionary = dict()

for eachItem in range(1, num + 1):
    result_dictionary[eachItem] = eachItem**3

print(result_dictionary)


"""
Output: 

Enter a number: 5      
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125}

"""

13. Write a program that asks for input from a list of items and converts it into a tuple. Display both sequences.

Solution:

input_items = input("Enter a list of items: ")
my_list = input_items.split(",")

my_tuple = tuple(my_list)

print(my_list)
print(my_tuple)

"""
Output:

Enter a list of items: apple,orange
['apple', 'orange']
('apple', 'orange')

"""

14. Given below is an object class “Dog” which takes in name and age as arguments in the constructor function. Write code for the following questions.

class Dog:
    # constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Class Object Attribute
    scientific_name = "Canis lupus familiaris"
  • Question 1: Instantiate 3 dogs from this class with names and ages.
  • Question 2: Print out the “scientific_name” attribute.
  • Question 3: Write a function to find the oldest dog.
  • Question 4: Print the following: “The oldest dog is x years old.” x will be the oldest dog’s age by using the function from the third question.

Solution:

# 1 Instantiate the Dog object with 3 dogs
Dog1 = Dog("Arnold", 2)
Dog2 = Dog("Stan", 4)
Dog3 = Dog("Hufflepuff", 6)

# 2 Print out class attribute
print(f"The scientific name for Dog is {Dog.scientific_name}")


# 3 Create a function that finds the oldest dog
def oldest_dog(*args):
    return max(args)


# 4 Print out: "The oldest dog is x years old." x will be the oldest dog's age by using the function from the third question."
print(f"The oldest dog is {oldest_dog(Dog1.age, Dog2.age, Dog3.age)} years old")

"""
Output:

The scientific name for Dog is Canis lupus familiaris
The oldest dog is 6 years old

"""

15. Write a program that accepts a sentence as input and prints out the words in alphabetical order. Make use of list comprehension in the program.

Solution:

words = [eachItem for eachItem in input("Enter a sentence: ").split(" ")]
words.sort()

print(f"Rearranged Sequence: {' '.join(words)}")

"""
Output:

Enter a sentence: hi how are you doing today
Rearranged Sequence: are doing hi how today you

"""

16. Write a program that takes in a sentence as input. The program should remove the repeated words and also arrange/sort the words alphanumerically.

Solution:

input_sentence = input("Enter a sentence: ")
words = [eachWord for eachWord in input_sentence.split(" ")]
print(" ".join(sorted(list(set(words)))))

"""
Output:

Enter a sentence: I felt happy because I saw the others were happy and because I knew I should feel happy
I and because feel felt happy knew others saw should the were

"""

17. Write a program that calculates the number of digits and letters of an input sentence.

Solution:

sentence = input("Enter a sentence with numbers as well: ")
letter_count, digit_count = 0, 0

for each in sentence:
    if each.isalpha():
        letter_count += 1
    elif each.isnumeric():
        digit_count += 1
print(
    f"Number of letters: {letter_count}\nNumber of digits: {digit_count}"
)  

"""
Output:

Enter a sentence with numbers as well: my name is alpha47
Number of letters: 13
Number of digits: 2

"""

18. Write a program that calculates the number of uppercase and lowercase letters in an input sentence.

Solution:

sentence = input("Enter a sentence with different cases: ")
num_upper, num_lower = 0, 0

for each in sentence:
    num_lower += each.islower()
    num_upper += each.isupper()

print(
    f"Numer of Upper Case Letters: {num_upper}\nNumer of Lower Case Letters: {num_lower}"
)


"""
Output:

Enter a sentence with different cases: HELLO My Name is QUINN
Numer of Upper Case Letters: 12
Numer of Lower Case Letters: 6

"""

19. Write a program to calculate the value of the sequence (z + zz + zzz + zzzz + zzzzz) where “z” is an input digit by the user.

Solution:

def calc_func(num):
    return sum(int(num * n) for n in range(1, 6))


digit_value = input("Enter a digit between 0 to 9: ")

print(f"The sequence total is: {calc_func(digit_value)}")

"""
Output:

Enter a digit between 0 to 9: 7
The sequence total is: 86415

"""

20. Using the reduce function from the Python functools module, write a program to calculate the value of the sequence (z + zz + zzz + zzzz + zzzzz) where “z” is an input digit by the user.

Solution:

from functools import reduce

input_digit = input("Enter a digit between 0 to 9: ")
total = reduce(
    lambda accumulator, eachItem: int(accumulator) + int(eachItem),
    [input_digit * i for i in range(1, 6)],
)

print(f"The sequence total with the reduce function is: {total}")

"""
Output:

Enter a digit between 0 to 9: 7
The sequence total with the reduce function is: 86415

"""

21. From the list of numbers provided by the user, write a program to find even numbers and print the cubes.

Solution:

my_list = input("Enter a list of numbers: ")

only_even_cubed_list = [
    str(int(eachNum) ** 3) for eachNum in my_list.split(",") if int(eachNum) % 2 == 0
]

print(f"The new list is: {','.join(only_even_cubed_list)}")

"""
Output:

Enter a list of numbers: 3,5,2,7,8
The new list is: 8,512

"""

22. Write a program that calculates the amount in a bank account based on transaction amounts provided as inputs.

Solution:

acc_balance = 0
confirm_msg = "Account balance Updated Successfully!"

while True:
    user_request = input(
        "B for Balance|| D for Deposit || W for Withdraw || E for Exit: "
    ).lower()

    if user_request == "d":
        add_balance = input("Enter deposit amount: ")
        acc_balance = acc_balance + int(add_balance)
        print(confirm_msg)

    elif user_request == "w":
        withdraw_amount = input("Enter withdrawal amount: ")
        acc_balance = acc_balance - int(withdraw_amount)
        print(confirm_msg)

    elif user_request == "b":
        print(acc_balance)

    else:
        quit()

"""

Output:

B for Balance|| D for Deposit || W for Withdraw || E for Exit: d
Enter deposit amount: 1200
Account balance Updated Successfully!
B for Balance|| D for Deposit || W for Withdraw || E for Exit: w
Enter withdrawal amount: 500
Account balance Updated Successfully!
B for Balance|| D for Deposit || W for Withdraw || E for Exit: b
700
B for Balance|| D for Deposit || W for Withdraw || E for Exit: e

"""

23. Write a Python class and a generator that can traverse through a range of numbers divisible by 3 and print out those numbers.

Solution:

class CalcFunc:
    def three_divisor(self, num):
        for eachNum in range(1, num + 1):
            if eachNum % 3 == 0:
                yield eachNum


my_instance = CalcFunc()

user_number = int(input("Enter a number: "))

generator_function = my_instance.three_divisor(user_number)

for eachItem in generator_function:
    print(eachItem)

"""
Output:

Enter a number: 10
3
6
9

"""

24. Write a program to count the number of occurrences of each word in user input. Also, print the result with the keys sorted alpha-numerically. See the example input and output statement below.

Input: I bought 3 oranges and finished eating all 3 of them.

Expected Output:

'3' x 2 times
'I' x 1 times
'all' x 1 times
'and' x 1 times
'bought' x 1 times
'eating' x 1 times
'finished' x 1 times
'of' x 1 times
'oranges' x 1 times
'them.' x 1 times

Solution:

user_input_sentence = input("Enter a sentence: ")
splitted = user_input_sentence.split()

unique_and_sorted = sorted(set(splitted))

for eachItem in unique_and_sorted:
    print(f"'{eachItem}' x {user_input_sentence.count(eachItem)} times")


"""
Output:

Enter a sentence: I bought 3 oranges and finished eating all 3 of them.
'3' x 2 times
'I' x 1 times
'all' x 1 times
'and' x 1 times
'bought' x 1 times
'eating' x 1 times
'finished' x 1 times
'of' x 1 times
'oranges' x 1 times
'them.' x 1 times

"""

25. How can we see the built-in function docs in Python? Give examples. Also, write a document for a custom-defined function.

print(float.__doc__)
# Output: Convert a string or number to a floating point number, if possible.

print(abs.__doc__)
# Output: Return the absolute value of the argument.
def cube(num):
    """
    Docstring: Returns the cube of a number
    """
    return num**3


print(cube(5))
print(cube.__doc__)

"""
Output:

125

    Docstring: Returns the cube of a number

"""

26. Write a program to convert the temperature from Celcius to Fahrenheit and vice-versa. Formula: Celcius = (5 / 9) * (Fahrenheit - 32)

Solution:

input_temperature = float(input("Enter a temperature value: "))
input_unit = input(
    "Choose a unit for the above temperature: C for Celcuis || F for Fahrenheit: "
)


if input_unit == "C" or input_unit == "c":
    temp_in_F_units = 9 / 5 * input_temperature + 32
    print(f"Temperature in Fahrenheit is {temp_in_F_units}")

elif input_unit == "F" or input_unit == "f":
    temp_in_C_units = 5 / 9 * (input_temperature - 32)
    print(f"Temperature in Celsius is {temp_in_C_units}")
else:
    print("Invalid unit provided")

"""
Output:

Enter a temperature value: 40
Choose a unit for the above temperature: C for Celcuis || F for Fahrenheit: c
Temperature in Fahrenheit is 104.0

"""

27. Write a program to calculate the sum of cubes of first n natural numbers provided as an input parameter.

Solution:

def series_summation_func(num):
    accumulated_sum = 0

    for eachNum in range(1, num + 1):
        accumulated_sum += eachNum**3

    return accumulated_sum


print(series_summation_func(4))  # Output: 100
print(series_summation_func(5))  # Output: 225

28. Write a program to check if the user input number is prime or not.

Solution:

user_input = int(input("Please enter a number: "))

is_prime = True

if user_input > 1:
    # Factor Checking
    for each in range(2, user_input):
        if user_input % each == 0:
            is_prime = False
            break

if is_prime:
    print(f"{user_input} is a prime number.")
else:
    print(f"{user_input} is a not prime number.")


"""
Output: 

Please enter a number: 23
23 is a prime number.

"""

29. Write a function to calculate the area of a circle with the user input radius.

Solution:

def calc_circle_area(radius):
    PI = 3.147
    return PI * (radius**2)


input_radius = float(input("Please enter a radius value: "))
print(f"Area of the circle is {calc_circle_area(input_radius)} ")

"""
Output:

Please enter a radius value: 10
Area of the circle is 314.7

"""

30. Write a program to find the highest even number from a given list of numbers.

Solution:

my_list = [11, 2, 3, 4, 14, 8, 10]


def highest_even_func(lst):
    even_list = []

    for eachItem in lst:
        if eachItem % 2 == 0:
            even_list.append(eachItem)

    return max(lst)


val = highest_even_func(my_list)
print(f"Highest even number in the list is {val}")

# Output: Highest even number in the list is 14

31. Write a program to find the duplicates from a given list and print those items in a new list.

Solution:

my_list = ["a", "a", "b", "c", "a", "e", "d", "c", "c", "e"]

list_of_duplicates = []

for eachItem in my_list:
    if my_list.count(eachItem) > 1:
        if eachItem not in list_of_duplicates:
            list_of_duplicates.append(eachItem)

print(list_of_duplicates)  # Output: ['a', 'c', 'e']

32. Using list comprehension, write the same program as above to print out a new list of duplicate items from a given list.

Solution:

some_random_list = ["b", "n", "m", "n", "a", "b", "c"]

list_with_duplicate_items = list(
    set([value for value in some_random_list if some_random_list.count(value) > 1])
)
print(list_with_duplicate_items)

# Output: ['b', 'n']

33. Write a program that converts all the list items raised to the power of 2 and outputs a new list.

Solution:

my_list = [12, 10, 31, 4, 7]

def squared(item):
    return item**2

mapped = map(squared, my_list)

print(f"Original List: {my_list}")
print(f"Squared List: {list(mapped)}")

"""
Output:

Original List: [12, 10, 31, 4, 7]
Squared List: [144, 100, 961, 16, 49]

"""

34. How is the reduce function used in Python? Show an example.

Solution:

from functools import reduce

my_list = [1, 2, 3, 4]

def add_numbers(accumulator, number):
    return accumulator + number

# reduce(function, iterable, initial_value)
result_obtained = reduce(add_numbers, my_list, 10)

print(f"Accumulated Result is {result_obtained}")

# Output: Accumulated Result is 20

35. Write a program to check whether an input string is a palindrome or not.

Solution:

my_str = input("Enter a string: ")

my_str = my_str.lower()

rev_str = reversed(my_str)

if list(my_str) == list(rev_str):
    print("The input string is a palindrome.")
else:
    print("The input string is not a palindrome.")


"""
Output:

Enter a string: MAlAYaLAm
The input string is a palindrome.

"""

Conclusion

These were some of the top programming questions for the Python interview. Having a grip on the fundamental concepts and syntaxes to solve a given problem is very important. On top of that, it takes a considerable amount of time and hard work to get good at coding. So, good luck with your coding interview, and I hope that this article helped you in one way or the other to get a little better at solving Python programming questions. Happy Coding!