Python Coding Interview Questions
1. How do you debug a Python program?
2. What is <Yield> Keyword in Python?
3. How to convert a list into a string?
4. How to convert a list into a tuple?
5. How to convert a list into a set?
6. How to count the occurrences of a particular element in the list?
7. What is NumPy array?
8. How can you create Empty NumPy Array In Python?
9. What is a negative index in Python?
[Link] do you Concatenate Strings in Python?
Python Coding Interview Questions And
Answers
Python Interview Questions # 1) How do you debug a Python program?
Answer) By using this command we can debug a python program
$ python -m pdb [Link]
Python Interview Questions # 2) What is <Yield> Keyword in Python?
A) The <yield> keyword in Python can turn any function into a generator. Yields
work like a standard return keyword.
But it’ll always return a generator object. Also, a function can have multiple calls
to the <yield> keyword.
Example:
def testgen(index):
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
yield weekdays[index]
yield weekdays[index+1]
day = testgen(0)
print next(day), next(day)
Output: sun mon
Python Interview Questions # 3) How to convert a list into a string?
A) When we want to convert a list into a string, we can use the <”.join()> method
which joins all the elements into one and returns as a string.
Example:
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
listAsString = ‘ ‘.join(weekdays)
print(listAsString)
Python Interview Questions # 4) How to convert a list into a tuple?
A) By using Python <tuple()> function we can convert a list into a tuple. But we
can’t change the list after turning it into tuple, because it becomers immutable.
Example:
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]
listAsTuple = tuple(weekdays)
print(listAsTuple)
output: (‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’)
Python Interview Questions # 5) How to convert a list into a set?
A) User can convert list into set by using <set()> function.
Example:
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’,’sun’,’tue’]
listAsSet = set(weekdays)
print(listAsSet)
output: set([‘wed’, ‘sun’, ‘thu’, ‘tue’, ‘mon’, ‘fri’, ‘sat’])
Python Interview Questions # 6) How to count the occurrences of a
perticular element in the list?
A) In Python list, we can count the occurences of a individual element by using a
<count()> function.
Example # 1:
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]
print([Link](‘mon’))
Output: 3
Example # 2:
weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sun’,’mon’,’mon’]
print([[x,[Link](x)] for x in set(weekdays)])
output: [[‘wed’, 1], [‘sun’, 2], [‘thu’, 1], [‘tue’, 1], [‘mon’, 3], [‘fri’, 1]]
Python Interview Questions # 7) What is NumPy array?
A) NumPy arrays are more flexible then lists in Python. By using NumPy arrays
reading and writing items is faster and more efficient.
Python Interview Questions # 8) How can you create Empty NumPy Array
In Python?
A) We can create Empty NumPy Array in two ways in Python,
1) import numpy
[Link]([])
2) [Link](shape=(0,0))
Python Interview Questions # 9) What is a negative index in Python?
A) Python has a special feature like a negative index in Arrays and Lists. Positive
index reads the elements from the starting of an array or list but in the negative
index, Python reads elements from the end of an array or list.
Python Interview Questions # 10) What is the output of the below code?
>> import array
>>> a = [1, 2, 3]
>>> print a[-3]
>>> print a[-2]
>>> print a[-1]
A) The output is: 3, 2, 1
Advanced Python Coding Interview Questions
Python Coding Interview Questions # 11) What is the output of the below
program?
>>>names = [‘Chris’, ‘Jack’, ‘John’, ‘Daman’]
>>>print(names[-1][-1])
A) The output is: n
Python Coding Interview Questions # 12) What is Enumerate() Function in
Python?
A) The Python enumerate() function adds a counter to an iterable object.
enumerate() function can accept sequential indexes starting from zero.
Python Enumerate Example:
subjects = (‘Python’, ‘Interview’, ‘Questions’)
for i, subject in enumerate(subjects):
print(i, subject)
Output:
0 Python
1 Interview
2 Questions
Python Coding Interview Questions # 13) What is data type SET in Python
and how to work with it?
A) The Python data type “set” is a kind of collection. It has been part of Python
since version 2.4. A set contains an unordered collection of unique and immutable
objects.
# *** Create a set with strings and perform search in set
objects = {“python”, “coding”, “tips”, “for”, “beginners”}
# Print set.
print(objects)
print(len(objects))
# Use of “in” keyword.
if “tips” in objects:
print(“These are the best Python coding tips.”)
# Use of “not in” keyword.
if “Java tips” not in objects:
print(“These are the best Python coding tips not Java tips.”)
# ** Output
{‘python’, ‘coding’, ‘tips’, ‘for’, ‘beginners’}
5
These are the best Python coding tips.
These are the best Python coding tips not Java tips.
# *** Lets initialize an empty set
items = set()
# Add three strings.
[Link](“Python”)
[Link](“coding”)
[Link](“tips”)
print(items)
# ** Output
{‘Python’, ‘coding’, ‘tips’}
Python Coding Interview Questions # 14) How do you Concatenate Strings
in Python?
A) We can use ‘+’ to concatenate strings.
Python Concatenating Example:
# See how to use ‘+’ to concatenate strings.
>>> print(‘Python’ + ‘ Interview’ + ‘ Questions’)
# Output:
Python Interview Questions
Python Coding Interview Questions # 15) How to generate random
numbers in Python?
A) We can generate random numbers using different functions in Python. They are:
#1. random() – This command returns a floating point number, between 0 and 1.
#2. uniform(X, Y) – It returns a floating point number between the values given as
X and Y.
#3. randint(X, Y) – This command returns a random integer between the values
given as X and Y.
Python Coding Interview Questions # 16) How to print sum of the numbers
starting from 1 to 100?
A) We can print sum of the numbers starting from 1 to 100 using this code:
print sum(range(1,101))
# In Python the range function does not include the end given. Here it will exclude
101.
# Sum funtion print sum of the elements of range funtion, i.e 1 to 100.
Python Coding Interview Questions # 17) How do you set a global variable
inside a function?
A) Yes, we can use a global variable in other functions by declaring it as global in
each function that assigns to it:
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
Python Coding Interview Questions # 18) What is the output of the
program?
names1 = [‘Amir’, ‘Bear’, ‘Charlton’, ‘Daman’]
names2 = names1
names3 = names1[:]
names2[0] = ‘Alice’
names3[1] = ‘Bob’
sum = 0
for ls in (names1, names2, names3):
if ls[0] == ‘Alice’:
sum += 1
if ls[1] == ‘Bob’:
sum += 10
print sum
A) 12
Python Coding Interview Questions # 19) What is the output, Suppose list1
is [1, 3, 2], What is list1 * 2 ?
A) [1, 3, 2, 1, 3, 2]
Python Coding Interview Questions # 20) What is the output when we
execute list(“hello”)?
A) [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
Python Coding Interview Questions And Answers For
Experienced
21) Can you write a program to find the average of numbers in a list in Python?
A) Python Program to Calculate Average of Numbers:
n=int(input(“Enter the number of elements to be inserted: “))
a=[]
for i in range(0,n):
elem=int(input(“Enter element: “))
[Link](elem)
avg=sum(a)/n
print(“Average of elements in the list”,round(avg,2))
Output:
Enter the number of elements to be inserted: 3
Enter element: 23
Enter element: 45
Enter element: 56
Average of elements in the list 41.33
22) Write a program to reverse a number in Python?
A) Python Program to Reverse a Number:
n=int(input(“Enter number: “))
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print(“Reverse of the number:”,rev)
Output:
Enter number: 143
Reverse of the number: 341
23) Write a program to find sum of the digits of a number in Python?
A) Python Program to Find Sum of the Digits of a Number
n=int(input(“Enter a number:”))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
print(“The total sum of digits is:”,tot)
Output:
Enter a number:1928
The total sum of digits is: 20
24) Write a Python Program to Check if a Number is a Palindrome or not?
A) Python Program to Check if a Number is a Palindrome or Not:
n=int(input(“Enter number:”))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print(“The number is a palindrome!”)
else:
print(“The number isn’t a palindrome!”)
Output:
Enter number:151
The number is a palindrome!
25) Write a Python Program to Count the Number of Digits in a Number?
A) Python Program to Count the Number of Digits in a Number:
n=int(input(“Enter number:”))
count=0
while(n>0):
count=count+1
n=n//10
print(“The number of digits in the number are:”,count)
Output:
Enter number:14325
The number of digits in the number are: 5
26) Write a Python Program to Print Table of a Given Number?
A) Python Program to Print Table of a Given Number:
n=int(input(“Enter the number to print the tables for:”))
for i in range(1,11):
print(n,”x”,i,”=”,n*i)
Output:
Enter the number to print the tables for:7
7x1=7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
27) Write a Python Program to Check if a Number is a Prime Number?
A) Python Program to Check if a Number is a Prime Number:
a=int(input(“Enter number: “))
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(“Number is prime”)
else:
print(“Number isn’t prime”)
Output:
Enter number: 7
Number is prime
28) Write a Python Program to Check if a Number is an Armstrong Number?
A) Python Program to Check if a Number is an Armstrong Number:
n=int(input(“Enter any number: “))
a=list(map(int,str(n)))
b=list(map(lambda x:x**3,a))
if(sum(b)==n):
print(“The number is an armstrong number. “)
else:
print(“The number isn’t an arsmtrong number. “)
Output:
Enter any number: 371
The number is an armstrong number.
29) Write a Python Program to Check if a Number is a Perfect Number?
A) Python Program to Check if a Number is a Perfect Number:
n = int(input(“Enter any number: “))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print(“The number is a Perfect number!”)
else:
print(“The number is not a Perfect number!”)
Output:
Enter any number: 6
The number is a Perfect number!
Python Developer Interview Questions And Answers
30) Write a Python Program to Check if a Number is a Strong Number?
A) Python Program to Check if a Number is a Strong Number:
sum1=0
num=int(input(“Enter a number:”))
temp=num
while(num):
i=1
f=1
r=num%10
while(i<=r):
f=f*i
i=i+1
sum1=sum1+f
num=num//10
if(sum1==temp):
print(“The number is a strong number”)
else:
print(“The number is not a strong number”)
Output:
Enter a number:145
The number is a strong number.
31) Write a Python Program to Find the Second Largest Number in a List?
A) Python Program to Find the Second Largest Number in a List:
a=[]
n=int(input(“Enter number of elements:”))
for i in range(1,n+1):
b=int(input(“Enter element:”))
[Link](b)
[Link]()
print(“Second largest element is:”,a[n-2])
Output:
Enter number of elements:4
Enter element:23
Enter element:56
Enter element:39
Enter element:11
Second largest element is: 39
32) Write a Python Program to Swap the First and Last Value of a List?
A) Python Program to Swap the First and Last Value of a List:
a=[]
n= int(input(“Enter the number of elements in list:”))
for x in range(0,n):
element=int(input(“Enter element” + str(x+1) + “:”))
[Link](element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print(“New list is:”)
print(a)
Output:
Enter the number of elements in list:4
Enter element1:23
Enter element2:45
Enter element3:67
Enter element4:89
New list is:
[89, 45, 67, 23]
33) Write a Python Program to Check if a String is a Palindrome or Not?
A) Python Program to Check if a String is a Palindrome or Not:
string=raw_input(“Enter string:”)
if(string==string[::-1]):
print(“The string is a palindrome”)
else:
print(“The string isn’t a palindrome”)
Output:
Enter string:malayalam
The string is a palindrome
34) Write a Python Program to Count the Number of Vowels in a String?
A) Python Program to Count the Number of Vowels in a String:
string=raw_input(“Enter string:”)
vowels=0
for i in string:
if(i==’a’ or i==’e’ or i==’i’ or i==’o’ or i==’u’ or i==’A’ or i==’E’ or i==’I’ or
i==’O’ or i==’U’):
vowels=vowels+1
print(“Number of vowels are:”)
print(vowels)
Output:
Enter string:Hello world
Number of vowels are:
3
35) Write a Python Program to Check Common Letters in Two Input Strings?
A) Python Program to Check Common Letters in Two Input Strings:
s1=raw_input(“Enter first string:”)
s2=raw_input(“Enter second string:”)
a=list(set(s1)&set(s2))
print(“The common letters are:”)
for i in a:
print(i)
Output:
Enter first string:Hello
Enter second string:How are you
The common letters are:
H
e
o
1. What is the output of the following?
print("Hello {name1} and {name2}".format(name1='foo', name2='bin'))
a) Hello foo and bin
b) Hello {name1} and {name2}
c) Error
d) Hello and
View Answer
Answer: a
Explanation: The arguments are accessed by their names.
2. What is the output of the following?
print("Hello {0!r} and {0!s}".format('foo', 'bin'))
a) Hello foo and foo
b) Hello ‘foo’ and foo
c) Hello foo and ‘bin’
d) Error
View Answer
Answer: b
Explanation: !r causes the characters ‘ or ” to be printed as well.
3. What is the output of the following?
print("Hello {0} and {1}".format(('foo', 'bin')))
a) Hello foo and bin
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
c) Error
d) None of the mentioned
View Answer
Answer: c
Explanation: IndexError, the tuple index is out of range.
4. What is the output of the following?
print("Hello {0[0]} and {0[1]}".format(('foo', 'bin')))
a) Hello foo and bin
b) Hello (‘foo’, ‘bin’) and (‘foo’, ‘bin’)
c) Error
d) None of the mentioned
View Answer
Answer: a
Explanation: The elements of the tuple are accessed by their indices.
5. What is the output of the following?
print('The sum of {0} and {1} is {2}'.format(2, 10, 12))
a) The sum of 2 and 10 is 12
b) Error
c) The sum of 0 and 1 is 2
d) None of the mentioned
View Answer
Answer: a
Explanation: The arguments passed to the function format can be integers also.
6. What is the output of the following?
print('The sum of {0:b} and {1:x} is {2:o}'.format(2, 10, 12))
a) The sum of 2 and 10 is 12
b) The sum of 10 and a is 14
c) The sum of 10 and a is c
d) Error
View Answer
advertisement
7. What is the output of the following?
print('{:,}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
View Answer
8. What is the output of the following?
print('{:,}'.format('1112223334'))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
View Answer
Answer: d
Explanation: An integer is expected.
9. What is the output of the following?
print('{:$}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
View Answer
Answer: d
Explanation: $ is an invalid format code.
10. What is the output of the following?
print('{:#}'.format(1112223334))
a) 1,112,223,334
b) 111,222,333,4
c) 1112223334
d) Error
View Answer
Answer: c
Explanation: The number is printed as it is.
What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
designed to be highly readable. It uses English keywords frequently where as other languages
use punctuation, and it has fewer syntactical constructions than other languages.
Name some of the features of Python.
Following are some of the salient features of python −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large
applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
What is the purpose of PYTHONPATH environment variable?
PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where
to locate the module files imported into a program. It should include the Python source library
directory and the directories containing Python source code. PYTHONPATH is sometimes
preset by the Python installer.
What is the purpose of PYTHONSTARTUP environment variable?
PYTHONSTARTUP - It contains the path of an initialization file containing Python source
code. It is executed every time you start the interpreter. It is named as .[Link] in Unix and
it contains commands that load utilities or modify PYTHONPATH.
What is the purpose of PYTHONCASEOK environment variable?
PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive
match in an import statement. Set this variable to any value to activate it.
What is the purpose of PYTHONHOME environment variable?
PYTHONHOME − It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.
Is python a case sensitive language?
Yes! Python is a case sensitive programming language.
What are the supported data types in Python?
Python has five standard data types −
Numbers
String
List
Tuple
Dictionary
What is the output of print str if str = 'Hello World!'?
It will print complete string. Output would be Hello World!.
What is the output of print str[0] if str = 'Hello World!'?
It will print first character of the string. Output would be H.
What is the output of print str[2:5] if str = 'Hello World!'?What is the output of print str[2:] if str
= 'Hello World!'?
It will print characters starting from 3rd character. Output would be llo World!.
What is the output of print str * 2 if str = 'Hello World!'?
It will print string two times. Output would be Hello World!Hello World!.
What is the output of print str + "TEST" if str = 'Hello World!'?
It will print concatenated string. Output would be Hello World!TEST.
What is the output of print list if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?What is the output of
print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?What is the output of print list[1:3] if list = [
'abcd', 786 , 2.23, 'john', 70.2 ]?What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23,
'john', 70.2 ]?What is the output of print tinylist * 2 if tinylist = [123, 'john']?What is the output
of print list + tinylist * 2 if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and tinylist = [123, 'john']?
It will print concatenated lists. Output would be ['abcd', 786, 2.23, 'john', 70.200000000000003,
123, 'john'].
What are tuples in Python?
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
What is the difference between tuples and lists in Python?
The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and
their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated. Tuples can be thought of as read-only lists.
What is the output of print tuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print complete tuple. Output would be ('abcd', 786, 2.23, 'john', 70.200000000000003).
What is the output of print tuple[0] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print first element of the tuple. Output would be abcd.
What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).
What is the output of print tuple[2:] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?What is the
output of print tinytuple * 2 if tinytuple = (123, 'john')?
It will print tuple two times. Output would be (123, 'john', 123, 'john').
What is the output of print tuple + tinytuple if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) and
tinytuple = (123, 'john')?
It will print concatenated tuples. Output would be ('abcd', 786, 2.23, 'john',
70.200000000000003, 123, 'john').
What are Python's dictionaries?
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
How will you create a dictionary in python?
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
How will you get all the keys from the dictionary?How will you get all the values from the
dictionary?
Using [Link]() function, we can get all the values from the dictionary object.
print [Link]() # Prints all the values
How will you convert a string to an int in python?
int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.
How will you convert a string to a long in python?How will you convert a string to a float in
python?
float(x) − Converts x to a floating-point number.
How will you convert a object to a string in python?
str(x) − Converts object x to a string representation.
How will you convert a object to a regular expression in python?
repr(x) − Converts object x to an expression string.
How will you convert a String to an object in python?
eval(str) − Evaluates a string and returns an object.
How will you convert a string to a tuple in python?
tuple(s) − Converts s to a tuple.
How will you convert a string to a list in python?
list(s) − Converts s to a list.
How will you convert a string to a set in python?
set(s) − Converts s to a set.
How will you create a dictionary using tuples in python?
dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.
How will you convert a string to a frozen set in python?
frozenset(s) − Converts s to a frozen set.
How will you convert an integer to a character in python?
chr(x) − Converts an integer to a character.
How will you convert an integer to an unicode character in python?
unichr(x) − Converts an integer to a Unicode character.
How will you convert a single character to its integer value in python?
ord(x) − Converts a single character to its integer value.
How will you convert an integer to hexadecimal string in python?
hex(x) − Converts an integer to a hexadecimal string.
How will you convert an integer to octal string in python?
oct(x) − Converts an integer to an octal string.
What is the purpose of ** operator?
** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power
20 if a = 10 and b = 20.
What is the purpose of // operator?
// Floor Division − The division of operands where the result is the quotient in which the digits
after the decimal point are removed.
What is the purpose of is operator?
is − Evaluates to true if the variables on either side of the operator point to the same object and
false otherwise. x is y, here is results in 1 if id(x) equals id(y).
What is the purpose of not in operator?
not in − Evaluates to true if it does not finds a variable in the specified sequence and false
otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.
What is the purpose break statement in python?
break statement − Terminates the loop statement and transfers execution to the statement
immediately following the loop.
What is the purpose continue statement in python?
continue statement − Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
What is the purpose pass statement in python?
pass statement − The pass statement in Python is used when a statement is required syntactically
but you do not want any command or code to execute.
How can you pick a random item from a list or tuple?
choice(seq) − Returns a random item from a list, tuple, or string.
How can you pick a random item from a range?
randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop,
step).
How can you get a random number in python?
random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.
How will you set the starting value in generating random numbers?
seed([x]) − Sets the integer starting value used in generating random numbers. Call this function
before calling any other random module function. Returns None.
How will you randomizes the items of a list in place?
shuffle(lst) − Randomizes the items of a list in place. Returns None.
How will you capitalizes first letter of string?
capitalize() − Capitalizes first letter of string.
How will you check in a string that all characters are alphanumeric?
isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric
and false otherwise.
How will you check in a string that all characters are digits?
isdigit() − Returns true if string contains only digits and false otherwise.
How will you check in a string that all characters are in lowercase?
islower() − Returns true if string has at least 1 cased character and all cased characters are in
lowercase and false otherwise.
How will you check in a string that all characters are numerics?
isnumeric() − Returns true if a unicode string contains only numeric characters and false
otherwise.
How will you check in a string that all characters are whitespaces?
isspace() − Returns true if string contains only whitespace characters and false otherwise.
How will you check in a string that it is properly titlecased?
istitle() − Returns true if string is properly "titlecased" and false otherwise.
How will you check in a string that all characters are in uppercase?
isupper() − Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
How will you merge elements in a sequence?
join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a
string, with separator string.
How will you get the length of the string?
len(string) − Returns the length of the string.
How will you get a space-padded string with the original string left-justified to a total of width
columns?
ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a
total of width columns.
How will you convert a string to all lowercase?
lower() − Converts all uppercase letters in string to lowercase.
How will you remove all leading whitespace in string?
lstrip() − Removes all leading whitespace in string.
How will you get the max alphabetical character from the string?
max(str) − Returns the max alphabetical character from the string str.
How will you get the min alphabetical character from the string?
min(str) − Returns the min alphabetical character from the string str.
How will you replaces all occurrences of old substring in string with new string?
replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max
occurrences if max given.
How will you remove all leading and trailing whitespace in string?
strip([chars]) − Performs both lstrip() and rstrip() on string.
How will you change case for all letters in string?
swapcase() − Inverts case for all letters in string.
How will you get titlecased version of string?
title() − Returns "titlecased" version of string, that is, all words begin with uppercase and the
rest are lowercase.
How will you convert a string to all uppercase?
upper() − Converts all lowercase letters in string to uppercase.
How will you check in a string that all characters are decimal?
isdecimal() − Returns true if a unicode string contains only decimal characters and false
otherwise.
What is the difference between del() and remove() methods of list?
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know.
What is the output of len([1, 2, 3])?
3.
What is the output of [1, 2, 3] + [4, 5, 6]?
[1, 2, 3, 4, 5, 6]
What is the output of ['Hi!'] * 4?
['Hi!', 'Hi!', 'Hi!', 'Hi!']
What is the output of 3 in [1, 2, 3]?
True
What is the output of for x in [1, 2, 3]: print x?
123
What is the output of L[2] if L = [1,2,3]?
3, Offsets start at zero.
What is the output of L[-2] if L = [1,2,3]?
1, Negative: count from the right.
What is the output of L[1:] if L = [1,2,3]?
2, 3, Slicing fetches sections.
How will you compare two lists?
cmp(list1, list2) − Compares elements of both lists.
How will you get the length of a list?
len(list) − Gives the total length of the list.
How will you get the max valued item of a list?
max(list) − Returns item from the list with max value.
How will you get the min valued item of a list?
min(list) − Returns item from the list with min value.
How will you get the index of an object in a list?
[Link](obj) − Returns the lowest index in list that obj appears.
How will you insert an object at given index in a list?
[Link](index, obj) − Inserts object obj into list at offset index.
How will you remove last object from a list?
[Link](obj=list[-1]) − Removes and returns last object or obj from list.
How will you remove an object from a list?
[Link](obj) − Removes object obj from list.
How will you reverse a list?
[Link]() − Reverses objects of list in place.
How will you sort a list?
[Link]([func]) − Sorts objects of list, use compare func if given.
What is lambda function in python?
‘lambda’ is a keyword in python which creates an anonymous function. Lambda does not
contain block of statements. It does not contain return statements.
What we call a function which is incomplete version of a function?
Stub.
When a function is defined then the system stores parameters and local variables in an area of
memory. What this memory is known as?
Stack.
A canvas can have a foreground color? (Yes/No)
Yes.
Is Python platform independent?
No
There are some modules and functions in python that can only run on certain platforms.
Do you think Python has a complier?What are the applications of Python?
Django (Web framework of Python).
2. Micro Frame work such as Flask and Bottle.
3. Plone and Django CMS for advanced content Management.
What is the basic difference between Python version 2 and Python version 3?
Table below explains the difference between Python version 2 and Python version 3.
[Link] Section Python Version2 Python Version3
1. Print Print command can be Python 3 needs parentheses to
Function used without print any string. It will raise
parentheses. error without parentheses.
2. Unicode ASCII str() types and Unicode (utf-8) and it has two
separate Unicode() but byte classes −
there is no byte type
code in Python 2. Byte
Bytearray S.
3. Exceptions Python 2 accepts both Python 3 raises a SyntaxError in
new and old notations turn when we don’t enclose the
of syntax. exception argument in
parentheses.
4. Comparing It does not raise any It raises ‘TypeError’ as warning
Unorderable error. if we try to compare
unorderable types.
Which programming Language is an implementation of Python programming language designed
to run on Java Platform?
Jython
(Jython is successor of Jpython.)
Is there any double data type in Python?
No
Is String in Python are immutable? (Yes/No)
Yes.
Can True = False be possible in Python?
No.
Which module of python is used to apply the methods related to OS.?
OS.
When does a new block begin in python?
A block begins when the line is intended by 4 spaces.
Write a function in python which detects whether the given two strings are anagrams or not.
def check(a,b):
if(len(a)!=len(b)):
return False
else:
if(sorted(list(a)) == sorted(list(b))):
return True
else:
return False
Name the python Library used for Machine [Link] does pass operation do?Name the
tools which python uses to find bugs (if any).Write a function to give the sum of all the numbers
in list?
Sample list − (100, 200, 300, 400, 0, 500)
Expected output − 1500
Write a program in Python to reverse a string without using inbuilt function reverse string?
Program to reverse a string in given below −
def string_reverse(str1):
rev_str = ' '
index = len(str1) #defining index as length of string.
while(index>0):
rev_str = rev_str + str1[index-1]
index = index-1
return(rev_str)
print(string_reverse('1tniop'))
First we declare a variable to store the reverse string. Then using while loop and indexing of
string (index is calculated by string length) we reverse the string. While loop starts when index
is greater than zero. Index is reduced to value 1 each time. When index reaches zero we obtain
the reverse of string.
Write a program to test whether the number is in the defined range or not?
Program is −
def test_range(num):
if num in range(0, 101):
print(''%s is in range''%str(num))
else:
print(''%s is not in range''%str(num))
Output −
test_range(101)
101 is not in the range
To test any number in a particular range we make use of the method ‘if..in’ and else condition.
Write a program to calculate number of upper case letters and number of lower case letters?
Test on String: ''Tutorials POINT''
Program is −
def string_test(s):
a = { ''Lower_Case'':0 , ''Upper_Case'':0} #intiail count of lower and upper
for ch in s: #for loop
if([Link]()): #if-elif-else condition
a[''Lower_Case''] = a[''Lower_Case''] + 1
elif([Link]()):
a[''Upper_Case''] = a [''Upper_Case''] + 1
else:
pass
print(''String in testing is: '',s) #printing the statements.
print(''Number of Lower Case characters in String: '',a[''Lower_Case''])
print(''Number of Upper Case characters in String: '',a[''Upper_Case''])
Output −
string_test(''Tutorials POINT'')
String in testing is: Tutorials POINT
Number of Lower Case characters in String: 8
Number of Upper Case characters in String: 6