Python Interview Questions
1
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.
2
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.
3
What is PEP 8?PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more readable
4
How is Python interpreted?Python language is an interpreted language. Python program runs directly from the source code. It converts the source code that is written by the programmer into an intermediate language, which is again translated into machine language that has to be executed.
5
What are the tools that help to find bugs or perform the static analysis?PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the style and complexity of the bug. Pylint is another tool that verifies whether the module meets the coding standard.
6
What is the difference between list and tuple?The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed, for example., as a key for dictionaries.
7
What is pickling and unpickling?Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function. This process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
8
What are Python decorators?A Python decorator is a specific change that we make in Python syntax to alter functions easily.
9
What is Dict and List comprehensions are?They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
10
How are arguments passed by value or by reference?Everything in Python is an object, and all variables hold references to the objects. The reference values are according to the functions. Therefore, you cannot change the value of the references. However, you can change the objects if it is mutable.
11
Explain namespace in PythonIn Python, every name introduced has a place where it lives and can be hooked for. This is known as a namespace. It is like a box where a variable name is mapped to the object placed. Whenever the variable is searched out, this box will be searched to get the corresponding object.
12
In Python what are iterators?In Python, iterators are used to iterate a group of elements, containers like a list.
13
What is the unittest in Python?A unit testing framework in Python is known as unittest. It supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections, etc.
14
What is lambda in Python?It is a single expression anonymous function often used as inline function.
15
Explain pass in PythonPass means no-operation Python statement, or in other words, it is a place holder in a compound statement, where there should be a blank left, and nothing has to be written there.
16
Give example of dictionary items() methodDict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print("Students Name: %s" % list(Dict.items()))
17
What are all dictionary methods:Here is the list of dictionary methods:
- copy()
- update()
- items()
- sort()
- len()
- cmp()
- Str()
18
What is the reason behind using yield in Python?There are situations where sometimes people wish to have more thorough and fine access control over how much is to be read over in each iteration. To get better control in these cases it’s always the best idea to use iter and yield.
19
How can you explain the term Pythonpath?Python path is an environmental variable that is used in the case of the importing of a module. A module is introduced; the python path is used to check out the presence of the imported in all directories. With an interpreter, it is possible to decide which module is needed to load.
20
In Python, what is the usage of local variables and global variables?Global Variables: When variables are considered either outside a function or in global space, it is known as global variables. The fact, it is possible to access these variables from any function in the program.
Local Variables: When variables are considered inside a function, it is known as local variables. The fact, this variable is presented in the local space rather than in the global space.
21
How can you share global variables across modules?To share global variables across modules within a single program, create a special module. Import the config module in all modules of your application. The module will be available as a global variable across modules.
22
Explain how can you make a Python Script executable on Unix?To make a Python Script executable on Unix, you need to do two things,
Script file’s mode must be executable, and the first line must begin with # ( #!/usr/local/bin/python)
23
Explain how to delete a file in Python?By using a command
os.remove (filename) or os.unlink(filename)
24
What is docstring in Python?A Python documentation string is known as docstring, it is a way of documenting Python functions, modules, and classes.
25
What are generators in Python?The way of implementing iterators are known as generators. It is a normal function except that it yields expression in the function.
26
Explain slicing in Python?A mechanism to select a range of items from sequence types like list, tuple, strings etc., is known as slicing.
27
How can you convert a number to a string?In order to convert a number into a string, use the inbuilt function str(). If you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
28
How can you access a module written in Python from C?You can access a module written in Python from C by following method,
Module = PyImport_ImportModule("<modulename>");
29
What is the use of // operator in Python?It is a Floor Divisionoperator, which is used for dividing two operands with the result as a quotient showing only digits before the decimal point. For instance, 10//5 = 2 and 10.0//5.0 = 2.0.
30
Mention the use of the split function in PythonThe use of the split function in Python is that it breaks a string into shorter strings using the defined separator. It gives a list of all words present in the string.
31
Explain what is the common way for the Flask script to work?The common way for the flask script to work is:
- Either it should be the import path for your application
- Or the path to a Python file
32
Explain how you can access sessions in Flask?A session basically allows you to remember information from one request to another. In a flask, it uses a signed cookie so the user can look at the session contents and modify. The user can modify the session if only it has the secret key Flask.secret_key.
33
If you have multiple Memcache servers, and one of them fails that contain data, will it try to get them?The data in the failed server won’t get removed, but there is a provision for auto-failure, which you can configure for multiple nodes. Fail-over can be triggered during any kind of socket or Memcached server level errors and not during normal client errors like adding an existing key, etc.
34
Explain what is Dogpile effect? How can you prevent this effect?Dogpile effect is referred to the event when cache expires, and websites are hit by the multiple requests made by the client at the same time. This effect can be prevented by using a semaphore lock. In this system, when the value expires, the first process acquires the lock and starts generating a new value.
35
What are the common examples of exceptions in Python?The common examples of exceptions in Python are:
- Division by Zero
- Accessing a file that does not exist.
- Addition of two incompatible types
- Trying to access a nonexistent index of a sequence
- Removing the table from the disconnected database server.
- ATM withdrawal of more than the available amount
36
How to print the star(*) pattern without newline and space?Code to print the star(*) pattern without newline and space:
for i in range(0, 20): print('*', end="")
37
Python was developed in which year?It was developed in 1991.
38
Where to run Python code?You can run a Python code from the run option in the menu in an interpreter. A Python code can also run in command prompt code. It will run the program after entering the correct path of the file.
39
What are the common built-in data types in Python?Python supports the below-mentioned built-in data types:
Immutable data types:
- Number
- String
- Tupl
Mutable data types:
- List
- Dictionary
- set
40
What are Python packages?A Python package refers to the collection of different sub-packages and modules based on the similarities of the function.
41
Is indentation required in Python?Indentation in Python is compulsory and is part of its syntax.
All programming languages have some way of defining the scope and extent of the block of codes. In Python, it is indentation. Indentation provides better readability to the code, which is probably why Python has made it compulsory.
42
How to comment with multiple lines in Python?To add a multiple lines comment in python, all the line should be prefixed by #.
43
What type of language is python? Programming or scripting?Generally, Python is an all purpose Programming Language ,in addition to that Python is also Capable to perform scripting.
44
Is Python fully object oriented?Python does follow an object-oriented programming paradigm and has all the basic OOPs concepts such as inheritance, polymorphism, and more, with the exception of access specifiers. Python doesn’t support strong encapsulation (adding a private keyword before data members). Although, it has a convention that can be used for data hiding, i.e., prefixing a data member with two underscores.
45
What does *args and **kwargs mean?- What does *args and **kwargs mean?*args: It is used to pass multiple arguments in a function.
- **kwargs: It is used to pass multiple keyworded arguments in a function in python
46
How will you read a random line in a file?We can read a random line in a file using the random module.
For example:
import random def read_random(fname): lines = open(fname).read().splitlines() return random.choice(lines) print(read_random (‘hello.txt’))
47
How will you reverse a list in Python?The function list.reverse() reverses the objects of a list.
48
How will you convert a string to all lowercase?lower() function is used to convert a string to lowercase.
For Example:
demo_string='ROSES' print(demo_string.lower())
49
What is Polymorphism in Python?Polymorphism is the ability of the code to take multiple forms. Let’s say, if the parent class has a method named XYZ then the child class can also have a method with the same name XYZ having its own variables and parameters.
50
Define encapsulation in Python?encapsulation in Python refers to the process of wrapping up the variables and different functions into a single entity or capsule.Python class is the best example of encapsulation in python.