Wednesday, February 24, 2021

Python programming-oriented interview questions - from Multiple Companies

Python programming-oriented interview questions - from Multiple Companies

=====================================================================================

a = 1, 2, 3 "What will be the answer if you print 'a'?

 
Ans: (1, 2, 3) tuple of values

=====================================================================================

Python Interview Questions on Loops 

Given input: "Narendra Boyina"

Required output:

arendra Boyina

Nrendra Boyina

Naendra Boyina

Narndra Boyina

Naredra Boyina

Narenra Boyina

Naendra Boyina

Nrendra Boyina

x = "Narendra Boyina"

y = x.split()  # ["Narendra", "Boyina"]
for i in range(len(y[0])):
    y = x.replace(x[i],
"",1)
    
print(y)

=====================================================================================

"""Find the sum of the series 2 +22 + 222 + 2222 + .. n terms"""

num = int(input("Enter integer value, where you want to stop series : "))
start = 2
sum = 0
for i in range(1, num+1):
print(start, end=" ")
sum += start
start = (start * 10) + 2
print("\nSum of above series is:", sum)

console output:
Enter integer value, where you want to stop series : 4
2 22 222 2222 
Sum of above series is: 2468

=====================================================================================

"""W.A.P to reverse an integer"""

num = int(input("enter number"))
while num > 0:
    digit = num % 
10    
    
num = num // 10
    
print(digit, end="")
# OR
num = int(input("enter number"))
rev = 
0
while num > 0:
    rev = (rev * 
10) + num % 10
    
num //= 10

print(rev)


=====================================================================================

""" Write a Python function that accepts a string  and 

returns a matching string where every even letter is uppercase, and every odd letter is lowercase."""

def myfunc(value):
output = []
for i, letter in enumerate(value):
if i % 2==0:
output.append(letter.upper())
else:
output.append(letter)
return "".join(output)


print(myfunc("narendra"))

=====================================================================================

""" Write a Python function that accepts a string and

calculate the number of upper case letters and lower case letters."""

def test_str(str):
    d = {
'uppercase': 0, 'lowercase': 0}
    
for i in str:
        
if i.isupper():
            d[
'uppercase'] += 1
        
elif i.islower():
            d[
'lowercase'] += 1
    
else:
        
pass
    print
("upper case count {0}\nlower count {1}".format(d['uppercase'], d['lowercase']))


str = 
input("enter a string: ")
test_str(str)

=====================================================================================

""" W.A.P for Permutation of a given string using the inbuilt function"""

from itertools import permutations
s = "Narendra" # check with s="abc" you will get 6 permutations
ps = permutations(s)
count = 0
for i in ps:
print("".join(i))
count += 1
print(count) # 40320 permutations will get for Narendra

=====================================================================================

""" W.A.P to find the sum of elements in the list"""

list1 = [11, 5, 17, 18, 23]
print(sum(list1))

# --->or<---

list_1 = [11, 5, 17, 18, 23]

total = 0

for element in list_1:

    total += element  # total = total+i

print(total)

# --->or<---

req = 0
for i in range(0, len(list1)):
    req =req + list1[i]
print(req)

=====================================================================================

"""W.A.P to take a list of elements from the user/console """

"""Note: While giving i/p values via console give with spaces between each value"""

input_string = input("enter list values: ")  # by default, it will consider as string
input_list = input_string.split() # it will give list of strings
print(input_list)

# input via console: enter list values: narendra 55 6.7 mahalakshmi
# output: ['narendra', '55', '6.7', 'mahalakshmi']

"""W.A.P to take a list of numbers from the user/console """

input_string = input("Enter values by providing space b/w each value: ")  
input_list = input_string.split() # it w strings
# below code is for converting each string into integer available in the list
for i in range(len(input_list)):
input_list[i] =
int(input_list[i]) # convert each element to integer type and place in same index
print(input_list)

# input via console:
Enter values by providing space b/w each value: 44 65 23 44
# Output : [44, 65, 23, 44]

=====================================================================================

""" W.A.P. to check Armstrong number or not"""

num = int(input("enter a number:"))
sum = 0
temp = num
while temp > 0:
    digit = temp % 10
    sum = sum + digit**3
    temp = temp//10
if num == sum:
    print("given num is Armstrong number")
else:
    print("given number is not Armstrong")

=====================================================================================

"" W.A.P to get prime numbers between interval"""

start = int(input("enter"))
end =
int(input("enter"))
for i in range(start, end+1):
   
for j in range(2, i):
       
if i % j == 0:
           
break
    else
:
       
print(i, end=" ")

""" W.A.P to get prime number till given number"""


def prime(num):
   
for i in range(2, num + 1):
       
for j in range(2, i):
           
if i % j == 0:
               
break
        else
:
           
print(i, end=" ")

num = int(input("enter number:"))
prime(num)

=====================================================================================


=====================================================================================

""" W.A.P to reverse words in a given string in Python"""

def reverse_string():

    """This function gives reverse of a given string"""

    req_string = string.split()  # converted string to list

    req_string.reverse()

    result = " ".join(req_string)  # joined with none string

    return result

 

string = input("enter string:")

print(reverse_string())

=====================================================================================

""" W.A.P to print fibonacci series """


 def fibonacci(n):
     n1 = 0
     n2 = 1
     temp = 0
     while temp < n:
         print(temp, end=" ")
         n1 = n2
         n2 = temp
         temp = n1 + n2


 n = int(input(" enter number:"))
 fibonacci(n)

=====================================================================================

""" W.A.P to find whether a no is the power of two"""


def powerof_2(n):
   
if n == 1:
       
return True
    elif
n % 2 != 0 or n == 0:
        
return False
    return
powerof_2(n / 2)

n =
int(input("enter number"))
print(powerof_2(n))

=====================================================================================

"""W.A.P to display the only duplicates"""

from collections import Counter

list = [
1,2,3,2,3,4,5,6,7,7]
var =
Counter(list)
print(var)  # Counter({2: 2, 3: 2, 7: 2, 1: 1, 4: 1, 5: 1, 6: 1})
for char,times in var.items():
   
if times>1:
       
print(char,end=" ")

=====================================================================================

"""W.A.P to print duplicates from a list of integers"""


def duplicate_element():
   
"""This function gives duplicate elements from given list"""
   
repeated = []
   
for i in range(len(list)):
       
for j in range(i+1, len(list)):
           
if list[i] == list[j] and list[i] not in repeated:
                repeated.
append(list[i])
   
return repeated

list = [
1, 3, 3, 2, 4, 4, 5, 6, 6, 8, 7]
print(duplicate_element())

=====================================================================================

# W.A.P for printing range of float values (Zebra company asked me in 2021)


def test_range(start_val, end_val, step):
    total = start_val
    result =[]
   
while total<end_val:
            total = total+step
            result.
append("{:.2f}".format(total))

   
return result

result =
test_range(0.0, 5.0, 0.2)
print(result)

=====================================================================================

A = input (“Enter any number: \t”)            Ex: 7

B = input (“Enter any number: \t”)         Ex: 8
print(A*B)
 

Answer: Error

Reason: input function by default taken as strings

TypeError: can't multiply sequence by non-int of type 'str'

=====================================================================================

How do you replace a particular value/ string in a list, in multiple places simultaneously?

a= ["Hi",444, "hello",472, "good morning",732, "hello",74.5, "hello", 34]

for i in a:

    if i == "hello":

        a[a.index(i)] = "Narendra"

print(a)

=====================================================================================

""" W.A.P to replace vowels in a string with a successive alphabet of a vowel

Note: 1 ord() is a Built-in Method that Returns an integer of the Unicode character

Note: 2 chr() is a Built-in Method that Returns a Character (string) from an Integer

vowels_list = ["a", "e", "i", "o", "u"]

"""
data = input("Enter any string")
temp = []
for element in data:
if element in vowels_list : # identifying vowels
# converting vowel to ASCII add 1 then converting to string & appending into list
temp.append(chr(ord(
element) + 1))
    else:
temp.append(
element) # placing consonants in a list

required_output = "".join(temp)
print(required_output)

or

 x = input("Enter any string")

print("".join([(chr(ord(elem)+ 1)) if elem in ["a", "e", "i", "o", "u"] else elem for elem  in x]))

=====================================================================================

W.A.P. for converting paragraphs to lines using Python.

a = "LOCATE REPO_ENABLE, REPO_DISABLE, PERIODIC, POWER_UP, BATT_WARN, DISCONNECT,

SHUTDOWN, IGNITION_OFF, IGNITION_ON, GEOFENCE_ENTRY, GEOFENCE_EXIT, PARKING,

IDLING, IDLING_END, SPEEDING_END, SPEEDING, GIMPACT_DETECTED"         #paragraph

b=a.split(", ")     # converted into List

for i in b:

print(i)             # lines will be printed.

=====================================================================================

 Write a code to sort a numerical list in Python

list = ["2", "7", "4", "3"]
list = [int(i) for i in list] # used list comprehension
list.sort()
print(list)

=====================================================================================

W. A.P to insert a character at Nth position
def insert_char(user_string, pos, char):
temp = []
for i in user_string:
temp.append(i)
temp.insert(pos, char)
return "".join(temp)


user_string = input("Enter string: ")
pos = int(input("Enter position: "))
char = input("Enter character: ")
print(insert_char(user_string, pos, char))

=====================================================================================

""" W.A.P. to Find the missing numbers in the given list. 

Example: input_lst [1, 3, 5, 7] required output : [2, 4, 6, 8]"""

def validate_missing_num(lst):
flag = 0
missed_numbers = []
for n in range(1,11):
if n not in lst:
print(n," is missing")
flag += 1 # flag to count no of missing numbers
missed_numbers.append(n)
else:
continue
if flag == 0: # when flag is 0 print "no missing numbers"
print("Nothing is missing")
else:
print("missed numbers are :{}".format(missed_numbers))



input_lst = [1, 2, 4, 5, 8, 10]
validate_missing_num(input_lst)

=========================================================================

""" W.A.P to validate whether the given string is in the correct consecutive alphabet order or not?"""


def consecutive_str_validate(input_string):

    l = len(input_string)

    s = ''.join(sorted(input_string))

    for i in range(1, l):

        if ord(s[i]) - ord(s[i - 1]) != 1:

            return False

    return True


if _name_ == "_main_":

    input_string = "bcd"

    if consecutive_str_validate(input_string):

        print("true")

    else:

        print("false")

    input_string = "ghj"

    if consecutive_str_validate(input_string):

        print("true")

    else:

        print("false")


=====================================================================================

""" Write a Python function that takes a list and returns a new list with unique elements of the first list."""


def unique_list(data):
    req = []
    for element  in data:
        if element not in req:
            req.append(element)
 
    print(req)


data = [
5, 3, 1,3, 4, 5, 6, 6, 68, 8, 8, 8, 68]
unique_list(data)

=====================================================================================


Python Interview Questions on Recursive Functions 

W.A.P. to calculate the sum of a list of numbers or Recursive function example.


def sum(num):
if len(num) == 1:
# if only one element in the list, sum result will be equal to the element
return num[0]
else:
return num[0] + sum(num[1:])

print(sum([2, 5, 3, 6, 4]))

=====================================================================================

Python Interview Questions on Functions 

""" Write a Python function to sum all the numbers in a list"""
def 
addition(numbers):
    total = 0
    for i in numbers:
        total +=i
    
return total
numbers = [
3,5,2,7,5,8,8]
total = addition(numbers)

print(total)

=====================================================================================


""" Write a Python function to multiply all the numbers in a list"""
def multiply(numbers):
    mul = 
1
    
for num in numbers:
        mul *= num   # mul = mul*
    
print(mul)


multiply([4, 3, 5, -2])    # calling function

=====================================================================================


""" Write a Python function to calculate the factorial of a number"""
def factorial(n):
    
if n == 0:
        
print("1")
    
else:
        fac = 
1
        
for i in range(1, n+1):
            fac *= i  # fac = fac*i
        
print("factorial of", n, "is", fac)

n = 
int(input("enter a number :"))
factorial(n)

# --->or<---

import math
print(math.factorial(5))

=====================================================================================

What is An anagram? Explain with an example

An anagram is the result of rearranging the letters of a word or phrase to produce a new word or phrase,

using all the original letters exactly once;

for example, the word cautioned can be rearranged into education.

 def is_anagram (str1, str2):

    list_str1 = list(str1)
list_str1.sort()
list_str2 = list(str2)
list_str2.sort()
return (list_str1 == list_str2)

print(is_anagram("cautioned", "education"))
print(is_anagram("cat", "rat"))

                    Or

def anagram(str1, str2):
if sorted(str1) == sorted(str2):
print("given strings are anagram")
else:
print("given strings are not anagram")


anagram("cautioned", "education") # given strings are anagram
anagram("anagram", "annagaram") # given strings are not anagram

=====================================================================================

""" insert a character at nth position"""

def ins_char():
    user_string =
input("enter string")
    pos =
int(input("enter position"))
    char =
input("enter character")
    l = []
   
for i in user_string:
        l.
append(i)
    l.
insert(pos, char)
   
print("".join(l))


ins_char()

=====================================================================================

""" Sorting dictionaries based on value"""

a = {1:23,2:1,3:11}
print(sorted(a.items(), key = lambda x:x[1])) # [(2, 1), (3, 11), (1, 23)] list of tuples
print(dict(sorted(a.items(), key = lambda x:x[1]))) # converted into dictionary {2: 1, 3: 11, 1: 23}

=====================================================================================

""" Sorting list of lists based on the second element in each list"""

# Given input รจ [[1,3,5], [3,4,6], [1,2,3]]
# Required output 
รจ [[1, 2, 3], [1, 3, 5], [3, 4, 6]]
list_a=[[1,3,5], [3,4,6], [1,2,3]]
a = 
sorted(list_a,key = lambda x : x[1])
print(a) #[[1, 2, 3], [1, 3, 5], [3, 4, 6]]

=====================================================================================

import random


l = [
1, 2, "sree", 10, 3, "kanth", 4, 5, 6, 7]
x = random.
sample(l, 1)
l.
remove(x[0])  # x gives the list of number of sample values
print(x[0], " is removed from the list")
print(l)


"""--- using the pop function"""

l = [1, 2, "sree", 10, 3, "kanth", 4, 5, 6, 7]
print(l.pop(l.index(random.sample(l, 1)[0])))
print(x, l)

=====================================================================================

What will be the output for the following code 

def Narendra(x,*y,**z):
   
print(x)
   
print(*y)
   
print(**z)
Narendra(
15, 2, 3, 4, 5, "Bhagyasree", x =11, y=12, z=13)

=====================================================================================

# Python program to check the validation of the password

password as a combination of alphanumeric characters along with special characters, and check whether the password is valid or not with the help of f bew conditions.

Primary conditions for password validation :

1. Minimum 8 characters.

2. The alphabet must be between [a - z]

3. At least one alphabet should be in Upper Case [A-Z]

4. At least 1 number or digit between [0-9].

5. At least 1 character from [ _ or @ or $ ].

# Module of a regular expression is used with search()

 import re


password = "R@m@_f0rtu9e$"
flag = 0
while True:
if (len(password) < 8):
flag = -1
break
elif not re.search("[a-z]", password):
flag = -1
break
elif not re.search("[A-Z]", password):
flag = -1
break
elif not re.search("[0-9]", password):
flag = -1
break
elif not re.search("[_@$]", password):
flag = -1
break
elif re.search("\s", password):
flag = -1
break
else:
flag = 0
print("Valid Password")
break
if flag == -1:
print("Not a Valid Password")

=====================================================================================

def get_packet_list(cmd):

        '''

        returns Packet List. Used by other Keywords internally

        INPUT: `cmd`` :- Tshark command to be executed

        OUTPUT: Returns Packets as List of Dictionaries on success

        Usage:         Packet_list=get_packet_list(cmd)

        '''

        print(cmd)

        fh=os.popen(cmd)

        data_dict=dict()

        data_dict_list=[]

        index=0

        for eachLine in fh.readlines():

               eachLine = eachLine[:-1]   

               if index == 0:

                       headers = eachLine.split('|')

               else:

                       data_list = eachLine.split('|')

                       data_dict = dict(zip(headers, data_list))  

                       data_dict_list.append(data_dict)

               index +=1

        return data_dict_list

def tx_packets_count_per_second_from_source(pcap_file_path, source_ip_address):

     cmd = 'tshark -r {pcap_file_path} -E header=y -Y "(ip.src=={source_ip_address} and udp)" -E separator="|" -T fields -e frame.number -e frame.time_epoch'.format(pcap_file_path= pcap_file_path, source_ip_address= source_ip_address)

        print("Command to be executed : {cmd} ".format(cmd=cmd))

        response = get_packet_list(cmd)

        l = [i['frame.time_epoch'].split(".")[0] for i in response]

        dict_pkts = {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(i))):l.count(i) for i in l}

        df = pd.DataFrame(data=dict_pkts, index=["Tx_Pkts_count"])

        df = (df.T)

        df.to_excel("Tx_packets.xlsx",sheet_name="UDP_Tx_packets",index_label="Seconds")

 

 

Calling function:

==============

if __name__ == '__main__':

    pcap_file_path = r"C:\Narendra\23feb2022\-pktcap-2022-01-11_13.54.27.pcap"

    source_ip_address = "192.168.xx.xxx"

    tx_packets_count_per_second_from_source(pcap_file_path, source_ip_address)

 

output:

======

In Excel sheet you will get the number of UDP packets transmitted per second.

Example:

========

Seconds     Tx_Pkts_count

2022-01-11 13:54:45  8

2022-01-11 13:54:46  2

2022-01-11 13:54:47  2

2022-01-11 13:54:48  2

2022-01-11 13:54:49  2

2022-01-11 13:54:50  2

2022-01-11 13:54:51  2

2022-01-11 13:54:52  2

2022-01-11 13:54:53  2

2022-01-11 13:54:54  2

2022-01-11 13:54:55  2

2022-01-11 13:54:56  33

2022-01-11 13:54:57  51

2022-01-11 13:54:58  53

2022-01-11 13:54:59  52

=====================================================================================

def terminate_thread(cmd_pipe,  timeout):

         st_time = time.time()

         while not teminate_flag():

                 if (time.time() - st_time) > timeout:

                          try:

                                   cmd_pipe.terminate()

                          except:

                                   pass

                          break

 

 

def teminate_flag(value=-1):

         global terminate_flg

         if value < 0:

                 return terminate_flg

         else:

                 terminate_flg = value

 

def run_adb_command(cmd, adb_timeout = 300):

         """

         Runs ADB command and returns its output as a list of lines

         This method uses subprocess.Popen to run the command

         It waits for 300 secs for the command to get completed

         Commands like "adb shell" is not supported as this is blocked

         until user gives input. Do not use this method for adb commands which

         gives huge output data (for example 1 Kb of data)

         :param cmd: Command to be executed

         :return: list of lines

         """

         output = ''

         error = ''

         log_message("ADB_CMD", "{cmd}".format(cmd=cmd))

         cmd_pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.PIPE)

         st_time = time.time()

         teminate_flag(0)

         thr = threading.Thread(target=terminate_thread, args=(cmd_pipe, adb_timeout))

         thr.start()

 

         while cmd_pipe.poll() is None:

                 output += cmd_pipe.stdout.readline()

 

                 if (time.time() - st_time) > adb_timeout:

                          break

 

         teminate_flag(1)

         thr.join()

         print "Command run for {time:0.2f} secs".format(time = (time.time() - st_time) )

         try:

                 cmd_pipe.terminate()

         except:

                 pass

         (out, err) = cmd_pipe.communicate()

         output += out

         error += err

         if error:

                 print("run_adb_command:  Error {error} while running command ".format(error=error)

         return re.split(b"\n+", output))


=====================================================================================

import os

import glob

os.chdir(r"path of  directory")

file = glob.glob(".txt")

print(file)

=====================================================================================

Python Interview Questions on Files & Folders(directories) 


 """ W.A.P to count the number of lines in a text file """

file = open("Narendra.txt", "r")

print("Number of lines:", len(file.read().split("\n")))

### OR ###

print("Number of lines:", len(open("Narendra.txt", "r").readlines()))

=====================================================================================

 """ W.A.P to get only .txt/.json/.py/.xml/.xls files in the directory """

import os

def get_file_names_based_on_extension(path, extension):

    for root, dirs, files in os.walk(path):

        for file in files:

            if file.endswith(extension):

                print(file)

 

path = r"E:\Narendra_Training_Data\Automation_Training_Data\Narendra_python_Feb2021"

extension =".py"

get_file_names_based_on_extension(path,extension)

=====================================================================================

"""Create 15 folders & each folder should contain one text file"""

import os

name = input("Enter any name : ")

for i in range(1, 15):

x = name+"_"+str(i) # creating directory name

os.mkdir(x) # creating folder

os.chdir(x) # entering in to that directory

y = x+".txt" # creating file name

open(y,"a+") # creating a file

os.chdir(path)

x = y = ""

=====================================================================================

""W.A.P to cretae 15 directories, each directory should contain one sub directory, 

and that sub directory should contain one file with data"""


import os


def create_multi_lvl_dir_file(d_name, sub_d_name, f_name):
"""
Based on the input names provided by the used this function will create multi level directories
Also this function will create a file inside it along with some content
:param d_name: main directory name
:param sub_d_name: sub directory name
:param f_name: file name
:return: None
"""
root_path = os.getcwd()
for i in range(1, 16):
dir_name = d_name+"_"+str(i) # preparing directory name
os.mkdir(dir_name) # creating directory
os.chdir(dir_name) # moving into the directory
subdir_name = sub_d_name+"_"+str(i) # preparing sub directory name
os.makedirs(subdir_name) # creating sub directory
os.chdir(subdir_name) # moving into the sub directory
file_name = f_name+"_"+str(i)+".txt" # preparing file name
with open(file_name, "w+") as f_obj: # creating file
f_obj.write("This file created inside subdirectory") # writing content to the file
os.chdir(root_path)


d_name = input("Enter required directory name: ") # Narendra
sub_d_name = input("Enter required subdirectory name: ") # Mahalakshmi
f_name = input("Enter required file name: ") # Raj
create_multi_lvl_dir_file(d_name, sub_d_name, f_name) # calling function

=====================================================================================

"""W. A.P to create 20 directories, each directory should contain one text file & one directory, 

and each inner directory should have a file in it.

Note:The file names should be different in directories and content should be different in those files"""

def create_multi_lvl_dir_file(d_name, sub_d_name, f_name):
"""
:param d_name: main directory name
:param sub_d_name: sub directory name
:param f_name: file name
:return: None
"""
root_path = os.getcwd()
for i in range(1, 21):
dir_name = d_name+"_"+str(i) # preparing directory name
os.mkdir(dir_name) # creating directory
os.chdir(dir_name) # moving into the directory
subdir_name = sub_d_name+"_"+str(i) # preparing sub directory name
os.makedirs(subdir_name) # creating sub directory
file_name_fr_main_dir = subdir_name+".txt" # preparing file name
with open(file_name_fr_main_dir, "w+") as f_obj: # creating file in main directory
f_obj.write("This file created in main subdirectory") # writing content to the file
os.chdir(subdir_name) # moving into the sub directory
file_name = f_name+"_"+str(i)+".txt" # preparing file name
with open(file_name, "w+") as f_obj: # creating file
f_obj.write("This file created inside subdirectory") # writing content to the file
os.chdir(root_path)


d_name = input("Enter required directory name: ") # Narendra
sub_d_name = input("Enter required subdirectory name: ") # Mahalakshmi
f_name = input("Enter required file name: ") # Raj

create_multi_lvl_dir_file(d_name, sub_d_name, f_name) # calling function=

=====================================================================================

def replace_label_tester_names(command, execution_label, tester, password="AH64_uh1"):

    regex_patterns = {'execution_label': r'(--execution_label)(\s+)(\S+)',
'tester': r'(--tester)(\s+)(\S+)',
'password': r'(--password)(\s+)(\S*)'}

replacements = {'execution_label': r'\1\2' + execution_label,
'tester': r'\1\2' + tester,
'password': r'\1\2' + password}

updated_command = command
for arg in regex_patterns: # by default arg is key
updated_command = re.sub(regex_patterns[arg], replacements[arg], updated_command)

return updated_command


Request: If you find this information useful, please provide your valuable comments.

Sunday, January 10, 2021

General Python PEP-8 standards

PEP stands for Python Enhancement Proposal.
  • PEP-8, is a document that provides guidelines and best practices on how to write Python code. 
  • It was written in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan. 
  • The primary focus of PEP 8 is to improve the readability and consistency of Python code.

Note: C
learly  I will Update this page later once i got time. till that time follow below  links.

Link : https://www.datacamp.com/community/tutorials/pep8-tutorial-python-code#intro

Link :  https://www.python.org/dev/peps/pep-0008/


Thursday, January 7, 2021

Python Identifier Interview questions - Multiple choice

 ******** Identifiers Interview Questions **********


Is Python case sensitive when dealing with identifiers?

a) yes

b) no

c) machine dependent

d) none of the mentioned


Answer: a

Explanation: Case is always significant.


What is the maximum possible length of an identifier?

a) 31 characters

b) 63 characters

c) 79 characters

d) none of the mentioned


Answer: d

Extra Information: According to the references, Python Documentation: Identifiers, “Identifiers are unlimited in length.”

As a practical matter you should probably not use names longer than about a dozen characters

Identifiers can be of any length.


Which of the following is invalid?

a) _a = 1

b) __a = 1

c) __str__ = 1

d) none of the mentioned


Answer: d

Explanation: All the statements will execute successfully but at the cost of reduced readability.


Which of the following is an invalid variable?

a) my_string_1

b) 1st_string

c) foo

d) _

View Answer


Answer: b

Explanation: Variable names should not start with a number.


Which of the following is not a keyword?

a) eval

b) assert

c) nonlocal

d) pass


Answer: a

Explanation: eval can be used as a variable.


All keywords in Python are in

a) lower case

b) UPPER CASE

c) Capitalized

d) None of the mentioned


Answer: d

Explanation: True, False and None are capitalized while the others are in lower case.


Which of the following is true for variable names in Python?

a) unlimited length

b) all private members must have leading and trailing underscores

c) underscore and ampersand are the only two special characters allowed

d) none of the mentioned


Answer: a

Explanation: Variable names can be of any length.


Which of the following is an invalid statement?

a) abc = 1,000,000

b) a b c = 1000 2000 3000

c) a,b,c = 1000, 2000, 3000

d) a_b_c = 1,000,000


Answer: b

Explanation: Spaces are not allowed in variable names.


Which of the following cannot be a variable?

a) __init__

b) in

c) it

d) on


Answer: b

Explanation: in is a keyword.


Request: If you find this information useful, please provide your valuable comments.

Python Loops Interview questions - Multiple choice

Loops Interview questions:

=====================================================================

1. x = [“ab”, “cd”]

for i in x:

              i.upper()

print(x)

a) [‘ab’, ‘cd’] 

b) [‘AB’, ‘CD’] 

c) [None, None] 

d) none of the mentioned

Answer: a

Explanation: The function upper() does not modify a string in place, it returns a new string that isn’t being stored anywhere


2. x = ["ab", "cd"]

for i in x:

x.append(i.upper())

print(x)

a) [‘AB’, ‘CD’] 

b) [‘ab’, ‘cd’, ‘AB’, ‘CD’] 

c) [‘ab’, ‘cd’] 

d) none of the mentioned


Answer: d

Explanation: The loop does not terminate as new elements are being added to the list in each iteration.


3.  i = 1

while True:

if i%3 == 0:

break

print(i)

i + = 1  =รจ space is the error (+=)

a) 1 2

b) 1 2 3

c) error

d) none of the mentioned

 

Answer: c

Explanation: SyntaxError, there shouldn’t be a space between + and = in +=.

 

4.  i = 1

while True:

if i%0O7 == 0:

break

print(i)

i += 1

a) 1 2 3 4 5 6

b) 1 2 3 4 5 6 7

c) error

d) none of the mentioned


Answer: a

Explanation: Control exits the loop when i becomes 7.


5.  i = 5

while True:

if i%0O11 == 0:  # print(int(0O11)) ==> 9

break

print(i)

i += 1

a) 5 6 7 8 9 10

b) 5 6 7 8

c) 5 6

d) error


Answer: b

Explanation: 0O11 is an octal number.

 

6.  i = 5

while True:

if i%0O9 == 0:

break

print(i)

i += 1


a) 5 6 7 8

b) 5 6 7 8 9

c) 5 6 7 8 9 10 11 12 13 14 15 ….

d) error


Answer: d

Explanation: 9 isn’t allowed in an octal number

 

7.  i = 1

while True:

if i%2 == 0:

break

print(i)

i += 2

a) 1

b) 1 2

c) 1 2 3 4 5 6 ………………

d) 1 3 5 7 9 11 ……………..


Answer: d

Explanation: The loop does not terminate since i is never an even number.

 

8.  i = 2

while True:

if i%3 == 0:

break

print(i)


i += 2

a) 2 4 6 8 10 …

b) 2 4

c) 2 3

d) error


Answer: b

Explanation: The numbers 2 and 4 are printed. The next value of i is 6 which is divisible by 3 and hence control exits the loop.

 

9.  i = 1

while False:

if i%2 == 0:

break

print(i)


i += 2

a) 1

b) 1 3 5 7 …

c) 1 2 3 4 …

d) none of the mentioned


Answer: d

Explanation: Control does not enter the loop because of False.

 

10. True = False

while True:

print(True)

break

a) True

b) False

c) None

d) none of the mentioned


Answer: d

Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.


11. i = 0

while i < 5:

print(i)

i += 1

if i == 3:

break

else:

print(0)

a) 0 1 2 0

b) 0 1 2

c) error

d) none of the mentioned


Answer: b

Explanation: The else part is not executed if control breaks out of the loop.


12. i = 0

while i < 3:

print(i)

i += 1

else:

print(0)

a) 0 1 2 3 0

b) 0 1 2 0

c) 0 1 2

d) error


Answer: b

Explanation: The else part is executed when the condition in the while statement is false.


13. x = "abcdef"

while i in x:

print(i, end=" ")

a) a b c d e f

b) abcdef

c) i i i i i i …

d) error


Answer: d

Explanation: NameError, i is not defined.


14. x = "abcdef"

i = "i"

while i in x:

print(i, end=" ")

a) no output

b) i i i i i i …

c) a b c d e f

d) abcdef


Answer: a  

Explanation: “i” is not in “abcdef”


15. x = "abcdef"

i = "a"

while i in x:

print(i, end = " ")

a) no output

b) i i i i i i …

c) a a a a a a …

d) a b c d e f


Answer: c

Explanation: As the value of i or x isn’t changing, the condition will always evaluate to True.


16. x = "abcdef"

i = "a"

while i in x:

print('i', end = " ")

a) no output

b) i i i i i i …

c) a a a a a a …

d) a b c d e f


Answer: b

Explanation: As the value of i or x isn’t changing, the condition will always evaluate to True.


17. x = "abcdef"

i = "a"

while i in x:

x = x[:-1]

print(i, end = " ")

a) i i i i i i

b) a a a a a a

c) a a a a a

d) none of the mentioned


Answer: b

Explanation: The string x is being shortened by one character in each iteration.


18. x = "abcdef"

i = "a"

while i in x[:-1]:

print(i, end = " ")

a) a a a a a

b) a a a a a a

c) a a a a a a …

d) a


Answer: c

Explanation: String x is not being altered and i is in x[:-1]


19. x = "abcdef"

i = "a"

while i in x:

x = x[1:]

print(i, end = " ")

a) a a a a a a

b) a

c) no output

d) error


Answer: b

Explanation: The string x is being shortened by one character in each iteration.


20. x = "abcdef"

i = "a"

while i in x[1:]:

print(i, end = " ")

a) a a a a a a

b) a

c) no output

d) error


Answer: c

Explanation: i is not in x[1:].


21. x = 'abcd'

for i in x:

print(i)

x.upper()

a) a B C D

b) a b c d

c) A B C D

d) error


Answer: b

Explanation: Changes do not happen in-place, rather a new instance of the string is returned.


22. x = 'abcd'

for i in x:

print(i.upper())

a) a b c d

b) A B C D

c) a B C D

d) error


Answer: b

Explanation: The instance of the string returned by upper() is being printed.


23. x = 'abcd'

for i in range(x):

print(i)

a) a b c d

b) 0 1 2 3

c) error

d) none of the mentioned


Answer: c

Explanation: range(str) is not allowed.


24. x = 'abcd'

for i in range(len(x)):

print(i)

a) a b c d

b) 0 1 2 3

c) error

d) 1 2 3 4


Answer: b

Explanation: i takes values 0, 1, 2 and 3.


25. x = 'abcd'

for i in range(len(x)):

print(i.upper())

a) a b c d

b) 0 1 2 3

c) error

d) 1 2 3 4


Answer: c

Explanation: Objects of type int have no attribute upper()


26. x = 'abcd'

for i in range(len(x)):

i.upper()

print (x)

a) a b c d

b) 0 1 2 3

c) error

d) none of the mentioned


Answer: c

Explanation: Objects of type int have no attribute upper().


27. x = 'abcd'

for i in range(len(x)):

i.upper()

print (x)

a) a b c d

b) 0 1 2 3

c) error

d) none of the mentioned


Answer: c

Explanation: Objects of type int have no attribute upper().


28. x = 'abcd'

for i in range(len(x)):

i[x].upper()

print (x)

a) abcd

b) ABCD

c) error

d) none of the mentioned


Answer: c

Explanation: Objects of type int aren’t subscriptable. However, if the statement was x[i], 

an error would not have been thrown.


29. x = 'abcd'

for i in range(len(x)):

x = 'a'

print(x)


a) a

b) abcd abcd abcd

c) a a a a

d) none of the mentioned


Answer: c

Explanation: range() is computed only at the time of entering the loop.


30. x = 'abcd' 

for i in range(len(x)):

print(x)

x = 'a'


a) a

b) abcd abcd abcd abcd

c) a a a a

d) none of the mentioned


Answer: d

Explanation: abcd a a a is the output as x is modified only after ‘abcd’ has been printed once.


31. x = 123

for i in x:

print(i)


a) 1 2 3

b) 123

c) error

d) none of the mentioned


Answer: c

Explanation: Objects of type int are not iterable.


32. d = {0: 'a', 1: 'b', 2: 'c'}

for i in d:

print(i)


a) 0 1 2

b) a b c

c) 0 a 1 b 2 c

d) none of the mentioned


Answer: a

Explanation: Loops over the keys of the dictionary.


33. d = {0: 'a', 1: 'b', 2: 'c'}

for x, y in d:

print(x, y)


a) 0 1 2

b) a b c

c) 0 a 1 b 2 c

d) none of the mentioned


Answer: d

Explanation: Error, objects of type int aren’t iterable.


34. d = {0: 'a', 1: 'b', 2: 'c'}

for x, y in d.items():

print(x, y)


a) 0 1 2

b) a b c

c) 0 a 1 b 2 c

d) none of the mentioned


Answer: c

Explanation: Loops over key, value pairs.


35. d = {0: 'a', 1: 'b', 2: 'c'}

for x in d.keys():

print(d[x])


a) 0 1 2

b) a b c

c) 0 a 1 b 2 c

d) none of the mentioned


Answer: b

Explanation: Loops over the keys and prints the values.


36. d = {0: 'a', 1: 'b', 2: 'c'}

for x in d.values():

print(x)


a) 0 1 2

b) a b c

c) 0 a 1 b 2 c

d) none of the mentioned


Answer: b

Explanation: Loops over the values.


37. d = {0: 'a', 1: 'b', 2: 'c'}

for x in d.values():

print(d[x])


a) 0 1 2

b) a b c

c) 0 a 1 b 2 c

d) none of the mentioned


Answer: d

Explanation: Causes a KeyError.


38. d = {0, 1, 2}

for x in d.values():

print(x)


a) 0 1 2

b) None None None

c) error

d) none of the mentioned

Answer: c

Explanation: Objects of type set have no attribute values.


39. d = {0, 1, 2}

for x in d:

print(x)


a) 0 1 2

b) {0, 1, 2} {0, 1, 2} {0, 1, 2}

c) error

d) none of the mentioned


Answer: a

Explanation: Loops over the elements of the set and prints them.


40. d = {0, 1, 2}

for x in d:

print(d.add(x))


a) 0 1 2

b) 0 1 2 0 1 2 0 1 2 …

c) None None None

d) None of the mentioned


Answer: c

Explanation: Variable x takes the values 0, 1 and 2. set.add() returns None which is printed.

41. What will be the output of the following Python code?

values = [[3, 4, 5, 1], [33, 6, 1, 2]] 

v = values[0][0]

for row in range(0, len(values)):

for column in range(0, len(values[row])):

if v < values[row][column]:

v = values[row][column]

print(v)

a) 3

b) 5

c) 6

d) 33


Answer: d

Explanation: Execute in the shell to verify.


42. What will be the output of the following Python code?

values = [[3, 4, 5, 1], [33, 6, 1, 2]]

v = values[0][0]

for lst in values:

for element in lst:

if v > element:

v = element

print(v)

a) 1

b) 3

c) 5

d) 6


Answer: a

Explanation: Execute in the shell to verify.


43. What will be the output of the following Python code?

matrix = [[1, 2, 3, 4],

        [4, 5, 6, 7],

        [8, 9, 10, 11],

        [12, 13, 14, 15]]

for i in range(0, 4):

print(matrix[i][1], end = " ")

a) 1 2 3 4

b) 4 5 6 7

c) 1 3 8 12

d) 2 5 9 13


Answer: d

Explanation: Execute in the shell to verify.

45. What will be the output of the following Python code?

values = [[3, 4, 5, 1 ], [33, 6, 1, 2]]

for row in values:

row.sort()

for element in row:

print(element, end = " ")

a) The program prints two rows 3 4 5 1 followed by 33 6 1 2

b) The program prints on row 3 4 5 1 33 6 1 2

c) The program prints two rows 3 4 5 1 followed by 33 6 1 2

d) The program prints two rows 1 3 4 5 followed by 1 2 6 33


Answer: d

Explanation: Execute in the shell to verify.


46. What will be the output of the following Python code?

a= [1, 2, 3, 4, 5]

for i in range(1, 5):

a[i-1] = a[i]

for i in range(0, 5): 

print(a[i],end = " ")

a) 5 5 1 2 3

b) 5 1 2 3 4

c) 2 3 4 5 1

d) 2 3 4 5 5


Answer: d

Explanation: The items having indexes from 1 to 4 are shifted forward by one index due to 

the first for-loop and the item of index four are printed again because of the second for-loop.


47. What will be the output of the following Python code?

num = ['One', 'Two', 'Three']

for i, x in enumerate(num):

print('{}: {}'.format(i, x),end=" ")

a) 1: 2: 3:

b) Exception is thrown

c) One Two Three

d) 0: One 1: Two 2: ThreeV


Answer: d

Explanation: enumerate(iterator,start=0) is a built-in function which returns (0,lst[0]),(1,lst[1]) 

and so on where lst is a list(iterator).


48. What will be the output of the following Python code?

a = [1, 5, 7, 9, 9, 1]

b = a[0]   # b=1

x= 0

for x in range(1, len(a)):            # for x in range(1, 6)

if a[x] > b:

b = a[x]

b = x

print(b)

a) 5

b) 3

c) 4

d) 0


Answer: c

Explanation: The above piece of code basically prints the index of the largest element in the list.

49. What will be the output of the following Python code snippet?

a={1:"A", 2:"B", 3:"C"}

for i,j in a.items():

print(i,j,end=" ")

a) 1 A 2 B 3 C

b) 1 2 3

c) A B C

d) 1:”A” 2:”B” 3:”C”


Answer: a

Explanation: In the above code, variables i and j iterate over the keys and values of the dictionary respectively

50. What will be the output of the following Python code?

a={1:"A",2:"B",3:"C"}

for i in a:

print(i,end=" ")


a) 1 2 3

b) ‘A’ ‘B’ ‘C’

c) 1 ‘A’ 2 ‘B’ 3 ‘C’

d) Error, it should be: for i in a.items():


Answer: a

Explanation: The variable I iterates over the keys of the dictionary and hence the keys are printed.

51. What will be the output of the following Python code snippet?

a = {}

a[1] = 1

a['1'] = 2

a[1]=a[1]+1

count = 0

for i in a:

count += a[i]

print(count)

a) 1

b) 2

c) 4

d) Error, the keys can’t be a mixture of letters and numbers


Answer: c

Explanation: The above piece of code basically finds the sum of the values of keys.


52. What will be the output of the following Python code snippet?

a = {}

a[1] = 1

a['1'] = 2

a[1.0]=4

count = 0

for i in a:

count += a[i]

print(count)

a) An exception is thrown

b) 3

c) 6

d) 2


Answer: c

Explanation: The value of key 1 is 4 since 1 and 1.0 are the same. 

Then, the function count() gives the sum of all the values of the keys (2+4).