A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_interview_questions.htm below:

Python Interview Questions and Answers

Python Interview Questions and Answers

Dear readers, these Python Programming Language Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of Python Programming Language. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −

Python Basics Interview Questions 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 −

Is Python a case-sensitive language?

Yes, Python is a case-sensitive language. Which means identifiers, function names, and keywords that has to be distinguished based on the capitalization. Case-sensitivity also helps to maintain the clarity and precision in the code.

Is the Python platform independent?

Yes, Python is platform-independent. In Python code runs in any operating system with a compatible interpreter. Python codes are executed by the interpreter that abstracts the hardware and Operating system in detail.

What are the applications of Python?

Following are the applications of Python −

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.

S.No Section Python Version2 Python Version3 1. Print Function

Print command can be used without parentheses.

Python 3 needs parentheses to print any string. It will raise error without parentheses.

2. Unicode

ASCII str() types and separate Unicode() but there is no byte type code in Python 2.

Unicode (utf-8) and it has two byte classes −

3. Exceptions

Python 2 accepts both new and old notations of syntax.

Python 3 raises a SyntaxError in turn when we don't enclose the exception argument in parentheses.

4. Comparing Unorderable

It does not raise any error.

It raises TypeError' as warning if we try to compare unorderable types.

Is there any double data type in Python?

No, Python doesn't have a double datatype. Python uses float type for floating-point numbers, that determines the double precision default.

Are strings in Python immutable? (Yes/No)

Yes, strings in Python are immutable.

Can True = False be possible in Python?

No, True cannot be equal to False in Python. In Python True and False are different boolean values.

Python Environment Variables Interview Questions 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 .pythonrc.py 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.

Python Data Types and Operations Interview Questions What are the supported data types in Python?

Python has five standard data types −

What is the output of print str if str = 'Hello World!'?

Assigning Hello world to string.

str = 'Hello World!"
print(str)
Output
Hello World!
What is the output of print str[0] if str = 'Hello World!'?

Here, indexing starts from 0 in Python.

str = 'Hello World!"
print(str[0])
Output
H
What is the output of print str[2:5] if str = 'Hello World!'?
str = 'Hello World!'
print(str[2:5])
Output
llo
What is the output of print str[2:] if str = 'Hello World!'?
str = 'Hello World!'
print(str[2:])
Output
llo World!
What is the output of print str * 2 if str = 'Hello World!'?
str = 'Hello World!'
print(str * 2)
Output
Hello World!Hello World!
What is the output of print str + "TEST" if str = 'Hello World!'?
str = 'Hello World!'
print(str + TEST)
Output
Hello World!TEST
What is the output of print list if list = ['abcd', 786 , 2.23, 'john', 70.2 ]?
list = ['abcd', 786 , 2.23, 'john', 70.2 ]
print(list)
Output
['abcd', 786 , 2.23, 'john', 70.2 ]
What is the output of print list[0] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
list = ['abcd', 786 , 2.23, 'john', 70.2 ]
print(list[0])
Output
abcd
What is the output of print list[1:3] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
list = ['abcd', 786 , 2.23, 'john', 70.2 ]
print(list[1:3])
Output
[786, 2.23]
What is the output of print list[2:] if list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]?
list = ['abcd', 786 , 2.23, 'john', 70.2 ]
print(list[2:])
Output
[2.23, 'john', 70.2]
What is the output of print tinylist * 2 if tinylist = [123, 'john']?
tinylist = [123, 'john']
print(tinylist * 2)
Output
[123, 'john', 123, 'john']
What is the output of print list1 + list2 if list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] and list2 = [123, 'john']?
list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ] 
list2 = [123, 'john']
print(list1 + list2)
Output
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples Interview Questions What are tuples in Python?

In Python, tuples are immutable sequence used to store multiple items. They cannot be modified after creation and are defined using parameters. Tuples are suitable for fixed collection of items.

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 )?
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
print(tuple)
Output
( 'abcd', 786 , 2.23, 'john', 70.2 )
What is the output of print tuple[0] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
print(tuple[0])
Output
abcd
What is the output of print tuple[1:3] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
print(tuple[1:3])
Output
(786, 2.23)
What is the output of print tuple[2:] if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
print(tuple[2:])
Output
(2.23, 'john', 70.2)
What is the output of print tinytuple * 2 if tinytuple = (123, 'john')?
tinytuple = (123, 'john')
print(tinytuple *2)
Output
(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')?
tuple = ('abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print(tuple + tinytuple)
Output
('abcd', 786 , 2.23, 'john', 70.2, 123, 'john')
Python Dictionaries Interview Questions 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?

Using dictionary.keys() function, we can get all the keys from the dictionary object.

print dict.keys()   # Prints all the keys
How will you get all the values from the dictionary?

Using dictionary.values() function, we can get all the values from the dictionary object.

print dict.values()   # Prints all the values
Python Strings Interview Questions How will you convert a string to an int in Python?

To convert a string into an integer in Python, we use 'int()' function. The string represents a valid integer, otherwise, it throws a ValueError.

How will you convert a string to a float in Python?

float()− converts the string to a float where the string must be a numeric value.

How will you convert an object to a string in Python?

str(x)− converts an object to a string

How will you convert an 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(str)−converts a string to a tuple.

tuple('Hello') 
Output
('H', 'e', 'l', 'l', 'o')
How will you convert a string to a list in Python?

list(str)− converts a string to a list.

print(list(Hello))
Output
['H', 'e', 'l', 'l', 'o']
How will you convert a string to a set in Python?

set(str)−converts a string to set and if there are any duplicated elements it will be removed.

print(set(Hello))
Output
{'e', 'o', 'H', 'l'}
How will you create a dictionary using tuples in Python?

dict(zip(tup1,tup2))−converts the tuples into a dictionary. zip() function is used to pair the tuples and dict() converters it into the dictionary.

tup1 = ('a', 'b', 'c', 'd')
tup2 = (1, 2, 3, 4)
dic =dict(zip(tup1,tup2))
print(dic)
Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
How will you capitalize the first letter of a string?

capitalize()−This method is used to convert the first character of a string to capital.

str1 = "tutorialspoint"
print(str1.capitalize())
Output
Tutorialspoint
How will you check if all characters in a string are alphanumeric?

isalnum()− Returns true if the string has at least 1 character and all characters are alphanumeric and false otherwise.

How will you check if all characters in a string are digits?

isdigit()− Returns true if the string contains only digits and false otherwise.

How will you check if all characters in a string are lowercase?

islower() − Returns true if the string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

How will you check if all characters in a string are numerics?

isnumeric()−Returns true if a Unicode string contains only numeric characters and false otherwise.

How will you check if all characters in a string are whitespaces?

isspace()−Returns true if the string contains only whitespace characters and false otherwise.

How will you check if a string is properly title-cased?

istitle()−Returns true if the string is properly "titlecased" and false otherwise.

How will you check if all characters in a string are uppercase?

isupper()− Returns true if the 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 a 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?

(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 a string to lowercase.

How will you remove all leading whitespace in a 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 replace all occurrences of an old substring in a string with a new string?

replace(): This method will replace every instance of the old substring with the new substring throughout the entire string.

str1 = "Welcome to tutorialspoint "
new_str =str1.replace("Welcome",'Hello Welcome')
print(new_str)
Output
Hello Welcome to tutorialspoint
How will you remove all leading and trailing whitespace in a string?

strip()− This method returns a new string with all leading (spaces at the beginning) and trailing (spaces at the end) whitespace removed.

str1 = "  Welcome to tutorialspoint  "
Str = str1.strip()
print(Str)
Output
Welcome to tutorialspoint
How will you change the case of all letters in a string? How will you get a title-cased version of the string?

title()− It is used to capitalize the first letter of each word of the string.

How will you convert a string to all uppercase?

upper()−used to convert all the letters of a string to Uppercase.

How will you check if all characters in a string are decimal?

isdecimal()− Returns true if a Unicode string contains only decimal characters and false otherwise.

Python Lists Interview Questions What is the difference between del() and remove() methods of a list?

The del() and remove() methods both are used to remove an element from a list. The del() is used to delete an element at a specified index value. It can also remove multiple elements using slicing operations. For example, The remove() method of a list is used to remove the first occurrence of an element.

List = [1,2,3,4,5,6]
#deleting an element
del List[1]
#deleting using sliding operation
del List[2:3]
#removing 5 
List.remove(5)
print(List)
Output
[1, 3, 6]
What is the output of len([1, 2, 3])?

The len() function returns the length of the list.(Output: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?

1 2 3

What is the output of L[2] if L = [1,2,3]?

3

What is the output of L[-2] if L = [1,2,3]?

2

What is the output of L[1:] if L = [1,2,3]?

3

How will you compare two lists?

To compare two lists, we need to use equality[ ==]. If both lists contain the same values, it will return True; otherwise, it will return False.

list1=[1,2,3,4]
list2=[1,2,3,4]
print(list1==list2)
Output
True
How will you get the length of a list?

Using the len() function we can find the length of the list.

list1 = [1,2,3,4,5]
print(len(list1))
Output
5
How will you get the max valued item of a list?

Using the max() function we can find the maximum element of the list.

list1 = [10, 20, 30, 40, 50]
print(max(list1))
Output
50
How will you get the min valued item of a list?

Using the min() function we can find the minimum element of the list.

list1 = [10, 20, 30, 40, 50]
print(min(list1))
Output
10
How will you get the index of an object in a list?

Using the index() function we can get the index value of an element.

list1 = [10, 20, 30, 40, 50]
print(list1.index(30))
Output
2
How will you insert an object at a given index in a list?

insert() function is used to insert an element at a particular index. It accepts index-value and object as parameters.

list1 = ['a', 'b', 'c', 'd','e']
list1.insert(3,'z')
Output
['a', 'b', 'c', 'z', 'd', 'e']
How will you remove the last object from a list?

pop() function is used to remove the last object from a list. We can also pass the index value as an argument and it returns the object at that specific index.

list1 = ['a', 'b', 'c', 'd','e']
list1.pop()
list1.pop(2)
print(list1)
Output
['a', 'b', 'd']
How will you remove an object from a list?

Using remove(), del(), and pop() we can remove an element from a list.

list1 = ['a', 'b', 'c', 'd','e']
list1.pop()
list1.pop(2)
print(list1)
Output
['a', 'b', 'd']
How will you reverse a list?

reverse() function is used to reverse a list. Using list slicing[::-1] we can also reverse the list.

list1 = ['a', 'b', 'c', 'd','e']
print(list1.reverse())
list2 = [1,2,3,4,5]
rev=list2[::-1]
print(rev)
Output
['e', 'd', 'c', 'b', 'a']
[5, 4, 3, 2, 1]
How will you sort a list?

Using sort() function is used to arrange the elements of the list in a specific order. By default, it arranges the elements in ascending order. To arrange the elements in descending order we can reverse the sorted list using the reverse() function.

list1 = [13,10,45,9,5,12]
list1.sort()
print(list1)
Output
[5, 9, 10, 12, 13, 45]
Python Operators Interview Questions What is the purpose of ** operator?What is Python?

The ** operator is used to perform exponential operations where a number is used to raise the power of another number. For example, 2**3 means 2 is raised to the power of 3.

What is the purpose of // operator?

// operator is used to perform floor division. It divides two numbers and returns the largest integer value less than or equal to the result of the division.

print(9//5)
Output
1
What is the purpose of is operator?

The is operator in Python is used to check if two variables refer to the same object in memory. It compares the identity of the objects, not their values.

What is the purpose of not in operator?

The not in operator in Python is used to check if a specific element is not present in a sequence, such as a list, tuple, string, or dictionary. If the element is not found, the operator returns True; otherwise, it returns False.

Python Control Statements Interview Questions What is the purpose of the break statement in Python?

The break statement is used to terminate the execution of a loop when a particular condition is met. Once the break statement is executed, the loop stops immediately, and the program continues with the next statement following the loop.

What is the purpose of the continue statement in Python?

The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and move directly to the next iteration of the loop. Unlike the break statement, which terminates the loop entirely, continue only skips to the next iteration without ending the loop.

What is the purpose of the pass statement in Python?

The Python pass is a null statement, which can be replaced with future code. It is used when we want to implement the function or conditional statements in the future, which has not been implemented yet. When we define a loop or function if we leave the block empty we will get an IndentationError so, to avoid this error we use pass.

Python Random Module Interview Questions How can you pick a random item from a list or tuple?

To pick a random item from a list or tuple in Python, we use the random.choice() function. This function returns a random selected element from the given list and tuple . This ensures us to import the random module by adding import random. This method id useful for selecting random samples, shuffling items, and creating simple games that require randomization.

How can you pick a random item from a range?

To pick a random item from a range in Python, we use random.choice() function. It returns a randomly selected element from the range 'start' to 'stop - 1'. This will also select the random number from the specified range.

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 randomize the items of a list in place?

shuffle(lst) − Randomizes the items of a list in place. Returns None.

Python Functions and Memory Interview Questions What is a 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 do we call a function which is an incomplete version of a function?

An incomplete version of a function is often called stub or partial function. These are typically a placeholder functions that may not have implementations or used during development for testing other parts of a code.

When a function is defined, the system stores parameters and local variables in an area of memory. What is this memory known as?

The memory area where parameters and local variables are stored in a function is defined as stack. Here, stack manages the function calls, stores the variables and returns the address of a particular file.

Python Modules and Libraries Interview Questions Which module of Python is used to apply the methods related to OS?

The OS module in Python is used to interact with the operating system. It provides file and directory manipulation, process management, environment variables, enables Python scripts to perform OS related tasks from different platforms.

Name the Python library used for Machine Learning.

The 'scikit-learn' library in Python is used for machine learning.

Name the tools Python uses to find bugs (if any).

Python uses several tools to find buys, they are −


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4