15 Mostly Asked Best Programming Questions in Python

These are some of the best or you can say basic Programming Questions in Python to start your learning and practice in python. So here are the 15 Programming Questions in Python.

1. Python program to add two numbers

# Python3 program to add two numbers

num1 = 15

num2 = 12

# Adding two nos

sum = num1 + num2

# printing values

print(“Sum of {0} and {1} is {2}” .format(num1, num2, sum))

output

2. Python Program for n-th Fibonacci number

# Function for nth Fibonacci number

def Fibonacci(n):

    if n<0:

        print(“Incorrect input”)

    # First Fibonacci number is 0

    elif n==1:

        return 0

    # Second Fibonacci number is 1

    elif n==2:

        return 1

    else:

        return Fibonacci(n-1)+Fibonacci(n-2)

# Driver Program

print(Fibonacci(9))

output

Programming Questions in Python

3. Python Program to find sum of array

# Python 3 code to find sum of elements in given array

def _sum(arr):

    # initialize a variable

    # to store the sum

    # while iterating through

    # the array later

    sum=0

    # iterate through the array

    # and add each element to the sum variable

    # one at a time

    for i in arr:

        sum = sum + i

    return(sum)

# driver function

arr=[]

# input values to list

arr = [12, 3, 4, 15]

# calculating length of array

n = len(arr)

ans = _sum(arr)

# display sum

print (‘Sum of the array is ‘, ans)

output

Programming Questions in Python

4. Python Program for Find remainder of array multiplication divided by n

# Find remainder of arr[0] * arr[1]

# * .. * arr[n-1]

def findremainder(arr, lens, n):

    mul = 1

    # find the individual

    # remainder and

    # multiple with mul.

    for i in arr:

        mul = mul * (i % n)

    return mul % n

# Driven code

arr = [100, 10, 5, 25, 35, 14]

lens = len(arr)

n = 11

print(findremainder(arr, lens, n))

output

Programming Questions in Python

5. Python program to interchange first and last elements in a list

# Python3 program to swap first

# and last element of a list

# Swap function

def swapList(newList):

    size = len(newList)

    # Swapping

    temp = newList[0]

    newList[0] = newList[size – 1]

    newList[size – 1] = temp

    return newList

# Driver code

newList = [12, 35, 9, 56, 24]

print(swapList(newList))

output

Programming Questions in Python

6. Python program to print negative numbers in a list

# Python program to print negative Numbers in a List

# list of numbers

list1 = [11, -21, 0, 45, 66, -93]

# iterating each number in list

for num in list1:

    # checking condition

    if num < 0:

       print(num, end = ” “)

output

Programming Questions in Python

7. Python – Remove empty List from List

# Python3 code to demonstrate

# Remove empty List from List

# using list comprehension

# Initializing list

test_list = [5, 6, [], 3, [], [], 9]

# printing original list

print(“The original list is : ” + str(test_list))

# Remove empty List from List

# using list comprehension

res = [ele for ele in test_list if ele != []]

# printing result

print (“List after empty list removal : ” + str(res))

output

Programming Questions in Python

8. Python | Cloning or Copying a list

# Python program to copy or clone a list

# Using the Slice Operator

def Cloning(li1):

    li_copy = li1[:]

    return li_copy

# Driver Code

li1 = [4, 8, 2, 10, 15, 18]

li2 = Cloning(li1)

print(“Original List:”, li1)

print(“After Cloning:”, li2)

output

Programming Questions in Python

9. Python program to multiply two matrices

# Program to multiply two matrices using nested loops

# take a 3×3 matrix

A = [[12, 7, 3],

    [4, 5, 6],

    [7, 8, 9]]

# take a 3×4 matrix   

B = [[5, 8, 1, 2],

    [6, 7, 3, 0],

    [4, 5, 9, 1]]

result = [[0, 0, 0, 0],

        [0, 0, 0, 0],

        [0, 0, 0, 0]]

# iterating by row of A

for i in range(len(A)):

    # iterating by coloum by B

    for j in range(len(B[0])):

        # iterating by rows of B

        for k in range(len(B)):

            result[i][j] += A[i][k] * B[k][j]

for r in result:

    print(r)

output

Programming Questions in Python

10. Python – Vertical Concatenation in Matrix

# Python3 code to demonstrate working of

# Vertical Concatenation in Matrix

# Using loop

# initializing lists

test_list = [[“Gfg”, “good”], [“is”, “for”], [“Best”]]

# printing original list

print(“The original list : ” + str(test_list))

# using loop for iteration

res = []

N = 0

while N != len(test_list):

    temp = ”

    for idx in test_list:

        # checking for valid index / column

        try: temp = temp + idx[N]

        except IndexError: pass

    res.append(temp)

    N = N + 1

res = [ele for ele in res if ele]

# printing result

print(“List after column Concatenation : ” + str(res))

output

Programming Questions in Python

11. Python program to check whether the string is Symmetrical or Palindrome

# Python program to demonstrate

# symmetry and palindrome of the

# string

# Function to check whether the

# string is plaindrome or not

def palindrome(a):

    # finding the mid, start

    # and last index of the string

    mid = (len(a)-1)//2

    start = 0

    last = len(a)-1

    flag = 0

    # A loop till the mid of the

    # string

    while(start<mid):

        # comparing letters from right

        # from the letters from left

        if (a[start]== a[last]):

            start += 1

            last -= 1

        else:

            flag = 1

            break;

    # Checking the flag variable to

    # check if the string is palindrome

    # or not

    if flag == 0:

        print(“The entered string is palindrome”)

    else:

        print(“The entered string is not palindrome”)

# Function to check whether the

# string is symmetrical or not       

def symmetry(a):

    n = len(a)

    flag = 0

    # Check if the string’s length

    # is odd or even

    if n%2:

        mid = n//2 +1

    else:

        mid = n//2

    start1 = 0

    start2 = mid

    while(start1 < mid and start2 < n):

        if (a[start1]== a[start2]):

            start1 = start1 + 1

            start2 = start2 + 1

        else:

            flag = 1

            break

    # Checking the flag variable to

    # check if the string is symmetrical

    # or not

    if flag == 0:

        print(“The entered string is symmetrical”)

    else:

        print(“The entered string is not symmetrical”)

# Driver code

string = ‘amaama’

palindrome(string)

symmetry(string)

output

Programming Questions in Python

12. Find the size of a Tuple in Python

import sys

# sample Tuples

Tuple1 = (“A”, 1, “B”, 2, “C”, 3)

Tuple2 = (“Geek1”, “Raju”, “Geek2”, “Nikhil”, “Geek3”, “Deepanshu”)

Tuple3 = ((1, “Lion”), ( 2, “Tiger”), (3, “Fox”), (4, “Wolf”))

# print the sizes of sample Tuples

print(“Size of Tuple1: ” + str(sys.getsizeof(Tuple1)) + “bytes”)

print(“Size of Tuple2: ” + str(sys.getsizeof(Tuple2)) + “bytes”)

print(“Size of Tuple3: ” + str(sys.getsizeof(Tuple3)) + “bytes”)

output

Programming Questions in Python

13. Python Program for Binary Search

# program for recursive binary search.

# Modifications needed for the older Python 2 are found in comments.

# Returns index of x in arr if present, else -1

def binary_search(arr, low, high, x):

    # Check base case

    if high >= low:

        mid = (high + low) // 2

        # If element is present at the middle itself

        if arr[mid] == x:

            return mid

        # If element is smaller than mid, then it can only

        # be present in left subarray

        elif arr[mid] > x:

            return binary_search(arr, low, mid – 1, x)

        # Else the element can only be present in right subarray

        else:

            return binary_search(arr, mid + 1, high, x)

    else:

        # Element is not present in the array

        return -1

# Test array

arr = [ 2, 3, 4, 10, 40 ]

x = 10

# Function call

result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:

    print(“Element is present at index”, str(result))

else:

    print(“Element is not present in array”)

output

Programming Questions in Python

14. Python Program for Linear Search

# Searching an element in a list/array in python

# can be simply done using \’in\’ operator

# Example:

# if x in arr:

# print arr.index(x)

# If you want to implement Linear Search in python

# Linearly search x in arr[]

# If x is present then return its location

# else return -1

def search(arr, x):

               for i in range(len(arr)):

                              if arr[i] == x:

                                             return i

               return -1

output

Programming Questions in Python

15. Python Program for Bubble Sort

# program for implementation of Bubble Sort

def bubbleSort(arr):

               n = len(arr)

               # Traverse through all array elements

               for i in range(n-1):

               # range(n) also work but outer loop will repeat one time more than needed.

                              # Last i elements are already in place

                              for j in range(0, n-i-1):

                                             # traverse the array from 0 to n-i-1

                                             # Swap if the element found is greater

                                             # than the next element

                                             if arr[j] > arr[j+1] :

                                                            arr[j], arr[j+1] = arr[j+1], arr[j]

# Driver code to test above

arr = [64, 34, 25, 12, 22, 11, 90]

bubbleSort(arr)

print (“Sorted array is:”)

for i in range(len(arr)):

               print (“%d” %arr[i]),

output

Programming Questions in Python

16. Python Program to Reverse a linked list

# program to reverse a linked list

# Time Complexity : O(n)

# Space Complexity : O(n) as ‘next’

#variable is getting created in each loop.

# Node class

class Node:

               # Constructor to initialize the node object

               def __init__(self, data):

                              self.data = data

                              self.next = None

class LinkedList:

               # Function to initialize head

               def __init__(self):

                              self.head = None

               # Function to reverse the linked list

               def reverse(self):

                              prev = None

                              current = self.head

                              while(current is not None):

                                             next = current.next

                                             current.next = prev

                                             prev = current

                                             current = next

                              self.head = prev

               # Function to insert a new node at the beginning

               def push(self, new_data):

                              new_node = Node(new_data)

                              new_node.next = self.head

                              self.head = new_node

               # Utility function to print the linked LinkedList

               def printList(self):

                              temp = self.head

                              while(temp):

                                             print temp.data,

                                             temp = temp.next

# Driver program to test above functions

llist = LinkedList()

llist.push(20)

llist.push(4)

llist.push(15)

llist.push(85)

print “Given Linked List”

llist.printList()

llist.reverse()

print “\nReversed Linked List”

llist.printList()

Programming Questions in Python

Accenture HR interview questions and answers for Freshers.:– Click Here

You can also run all these codes online by clicking here