Python (Interview Questions)

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 90

Python

~Interview Questions~
1.What is Python?
Python was created by Guido van Rossum, and released in 1991.

★ It is a general-purpose computer programming language.

★ It is a high-level, object-oriented language which can run equally on different

platforms such as Windows, Linux, UNIX, and Macintosh.

★ It is widely used in data science, machine learning and artificial intelligence

domain.

★ It is easy to learn and require less code to develop the applications


2.Why Python?
● Python is an interpreted, object-oriented, high-level programming language with

dynamic semantics.

● Python is compatible with different platforms like Windows, Mac, Linux,

Raspberry Pi, etc.

● Python has a simple syntax as compared to other languages.

● Python allows a developer to write programs with fewer lines than some other

programming languages.
3.what is the difference between c and python
C is a general-purpose, procedural computer programming language.
● It is statically typed language
● C Program syntax is harder than Python.
● C has a limited number of built-in functions.
● C programs are compiled by the compiler
● C is generally used for hardware related applications.

Python is an interpreted, high-level, general-purpose programming language.


● It is dynamically typed
● It is easier to write a code in Python as the number of lines is less comparatively.
● Python has a large library of built-in functions.
● interpreter is used in Python
● Python is a General-Purpose programming language
4.What are the applications of Python?
5.What do you mean by Python literals?

Literal is a raw data given in a variable or constant. In Python, there are


various types of literals they are as follows:
1)Numeric Literals

2) String literals

3) Boolean literals

4) Literal Collections(List, Tuple, Dict, Set ) Note: Dict : Dictionary


6.What is Python Identifiers?
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for writing identifiers
● Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore _.
● An identifier cannot start with a digit.
● Keywords cannot be used as identifiers
● We cannot use special symbols like !, @, #, $, % etc. in our identifier
7.What is Keyword?
1. Keywords are reserved words in python

2. We cannot use keyword as variable names, function names and any other identifier.

3. They are used to define syntax and structure of python language.

4. Keywords are case sensitive

5. There are 33 keywords in python 3.7

Eg: False,True ,class, is, return,while,for,def,continue….etc.


8.What is type conversion?
The process of converting the value of one data type (integer, string, float, etc.) to
another datatype is called type conversion.
Python has two types of type conversion.
1)Implicit Type Conversion
2)Explicit Type Conversion
9. What is Implicit Type Conversion?
1. In this method Python automatically converts one data type(lower) to
another data type(higher).
2. This process doesn't need any user involvement
10.what is Explicit Type Conversion?
● In Explicit Type Conversion, users convert the data type of an object to

required data type.

● We use the predefined functions like int(), float(), str(), etc to perform explicit

type conversion.

● This type of conversion is also called typecasting


11.What is Variable?
● Variables are just names of memory locations. Variables are used to store and
retrieve values from memory.
● Type of the variable is based on the value we assign to the variable.
a few rules to follow when choosing name of variable
● Names must start with a letter or underscore and can be followed by any number
of letters,digits, or underscores.
● Cannot start with a number
● It contain alpha-numeric characters & undescore.
● Variable names are case sensitive(age,Age,AGE are different).
● Names cannot be reserved words or keywords

Eg:x = 10,x=’python’,z=6.1
12.Input/Output Statements in python?
input():

The input() function allows user to give input.

Eg: a=int(input(“enter the value of a”))

Output():

This function is used to output the data or print the result on monitor

Eg: print(“Python”)
13. What are the Basic Data Types in python?
*Every value in Python has a datatype.
● Text Type: str

● Numeric Types: int, float, complex

● Sequence Types: list, tuple, range

● Mapping Type: dict

● Set Types: set, frozenset

● Boolean Type: bool


14.What is the use of type() function in python?
type(): To know the data type of any object by using the type() function.
15.What are Python Numbers?
They are categorized into mainly three types.

1. Int :It consists of positive and negative numbers without decimals

2. Float :It consists of positive and negative numbers containing decimals

numbers

3. Complex :Complex numbers in python are in the form of a + bj


16.What is Boolean datatype?
● Python provides Boolean datatype called bool with values True & False.
● True represents integer 1 and False represents integer 0.
17.What are Python Operators?
Operators are used to perform operations on variables and values.
1. Arithmetic operators

2. Assignment operators

3. Comparison operators

4. Logical operators

5. Identity operators

6. Membership operators

7. Bitwise operators
18.Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Example:
19.Python Comparison Operators
Comparison operators are used to compare two values
Example:
20.Python Logical Operators
Logical operators are used to combine conditional statements
Example:
21.Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if
they are actually the same object, with the same memory location:
Example:
22.Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Example:
23.Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers
Examples:
24. Python Assignment Operators
Assignment operators are used to assign values to variables:
Example:
25.What is operator precedence in Python?
Operator precedence in Python simply refers to the order of operations. Operators are
used to perform operations on variables and values.
26.What is Associativity of Python Operators?
● When two operators have the same precedence, associativity helps to
determine which the order of operations.
● Associativity is the order in which an expression is evaluated that has
multiple operator of the same precedence.
● Almost all the operators have left-to-right associativity

Eg : print(5 * 2 // 3) #L to R O/P: 3

“Exponent operator( **) has right-to-left associativity in Python”

Eg: print(2 ** 3 ** 2) # O/P: 512


27.What are Conditionals statements in python?
Decision Making Statements/Selection/Conditional Statements

❏ if statement
❏ if else statements
❏ elif ladder
❏ Nested if statements
28.What are Repetition Statements(loops) in python?

1.for loop

2, while loop
29. What is the use of Break and continue in python?
● In Python, break and continue statements can alter the flow of a normal

loop.

● Loops iterate over a block of code until test expression is false, but

sometimes we wish to terminate the current iteration or even the whole

loop without checking test expression.The break and continue statements

are used in these cases.


30.Python break statement
● The break statement terminates the loop containing it.
● Break statement in Python is used to bring the control out of the loop when
some external condition is triggered.
● Break statement is put inside the loop body (generally after if condition)..
31.Python continue statement
● The continue statement is used to skip the rest of the code inside a loop for the
current iteration only.
● Loop does not terminate but continues on with the next iteration.
32.What is Pep 8?

● PEP means “Python Enhancement Proposal”

● Code is read much more often than it is written.

● PEP 8 exists to improve the readability of Python code.

● It helps in writing clear and readable code.

● It helps in understanding the structure of the program


33.What is PIP, what is its use?

★ pip stands for "preferred installer program"


★ pip is a package-management system written in Python used to
install and manage software packages.
★ It connects to an online repository of public packages, called the
Python Package Index.
34. Is python scripting language or programming language?

★ Python is one of the best programming and scripting languages among all.

★ It doesn’t require any compilation and are directly interpreted.

★ The interpreter analyzes the entire program every time and halts the

execution if any error is encountered.


35. python is case sensitive language?

● Python is a case-sensitive language because it distinguishes between

identifiers like Variable and variable.

● In simple words, we can say it cares about uppercase and lowercase.


36. Interpreter vs Compiler

Interpreter Compiler
● It takes a single line of code ★ It takes an entire program at a
time.
● Slower ★ Comparatively fast
● It requires less memory as it does ★ Memory requirement is more due to
not create intermediate object code. the creation of object code.
● Displays error of each line one by ★ Displays all errors after compilation
one ,all at the same time
● Error Detection is Easy ★ Error Detection is Difficuilt
● Python,Perl,PHP,Ruby,etc., ★ C,C++,Java,Scala,etc.,
37 Difference between mutable and immutable.

mutable immutable
★ Mutable means, wecan change the ★ Immutable means, we cannot
values of a variable, which we change the values of a variable,
have stored. which we have stored.
★ mutable :List,Set,Dictionary ★ Immutable:Tuple,Strings,
Note: Numbers
*Set is mutable, but every element
is unique and must be immutable
*Keys in dictionary are unique and
they are immutable
(strings,numbers,tuples)
38.Difference between lists and tuple
List Tuple
★ List is a collection of ordered ★ Tuple is collection of ordered elements
elements,surrounded by square surrounded by round brackets().
brackets[]. ★ It is immutable(unchangeable)
★ List is mutable(changeable) ★ Tuples are fixed in length,
★ List is dynamic. They grow and shrink heterogeneous, and can be nested.
on demand. ★ Tuple data type is appropriate for
★ The list is better for performing accessing the elements
operations, such as insertion and ★ Tuple consume less memory as
deletion. compared to the list
★ Lists consume more memory ★ Tuple does no have must built-in
★ Lists have several built-in methods methods.
39.what is list comprehension
➢ Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, set, dictionary etc.) using sequences which have been already
defined.
➢ List comprehension allows us to create a new list of elements that satisfy a condition
from an iterable. An iterable is any Python construct that can be looped over like lists,
strings, tuples, sets. In list comprehensions we use square brackets

s=[x*x for x in range(1,11) if x%2==0]


Result of above comprehension will be:
[4, 16, 36, 64, 100]
40. what is list slicing
Slicing is used to build new lists out of an existing list.(or)Slicing is used to
extract part of a list
We can access a range of elements in a list by using the slicing operator
(colon) .
41. What are Dictionaries. Give examples
★ Python dictionary is an ordered collection of elements and it is mutable.
★ We can store values as a pair of keys and values
★ Represented by dict() or {}
★ Keys in dictionary are unique and they are immutable(strings,numbers,tuples)
42. difference between array and list

Arrays: Lists:
**An array is a data structure that holds **The list is written as the list of
fix number of elements and these commas separated values inside the
elements should be of the same data square bracket.
type.
**There are two important parts of the **The elements in the list are not
array: compulsory of the same datatype.
1. Element: Each item stored in the
array is called an element
**It can be represented with positive
2. Index: Every element in the array
index or negative index.
has its own numerical value to identify
the element.
43.What are Built in libraries in python?

The most important Python libraries are:


1. Numpy
2. Pandas
3. Matplotlib
4. Scikit-Learn
5. Scipy.
44.Explain Negative indexing in python.
➔ Negative indices allow you to refer to an item's position relative to the end of the
list.
➔ This means that the index value of -1 gives the last element, and -2 gives the
second last element of list.
➔ The negative indexing starts from where the list ends.
45.What is function? What are Built-in functions?
★ A function is a block of code which only runs when it is called. (or)
★ a function is a group of related statements that performs a specific task. (or)
★ A function is a block of organized and reusable program code that performs a
specific,single, and well-defined task.

Built-in-functions:

The Python built-in functions are defined as the functions whose functionality
is pre-defined in Python.

Eg: input(),print(),range(),len(),type(),sort(),etc.,
46.Use of functions in python?
➔ Functions help break our program into smaller and modular chunks.
➔ As our program grows larger and larger, functions make it more organized and
manageable.
➔ The idea is to put some commonly or repeatedly done tasks together and make a
function so that instead of writing the same code again and again for different
inputs.
➔ Understanding programs becomes easier.
➔ Users can create their own functions and use them in various locations in the
main program.
47.How to define Function in Python?
1. Function definition starts with the keyword def

2. The keyword def is followed by the function name and parentheses.

3. After parentheses, a colon (:) should be placed.

4. Parameters or arguments that the function accepts should be placed inside the
parentheses.

5. A function might have a return statement

def my_function():
print("Hello from a function")
48. Arguments
1. Arguments are the values passed inside the parentheses of the function.
2. A function can have any number of arguments separated by a comma..
3. Arguments are specified after the function name, inside the parentheses.
49.Difference between Parameters & Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.

From a function's perspective:


1. A parameter is the variable listed inside the parentheses in the
function definition.
2. An argument is the value that is sent to the function when it is called
50.Types of Arguments in python?

1. Positional Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable length Arguments
51. Positional Arguments?

Positional arguments are arguments that can be called by their position in the
function definition.
● First positional argument always needed to be listed first when the function is
called.
● Second positional argument always needed to be listed second when the
function is called and so on
52.Default Arguments in python?
➢Python allows function arguments to have default values.
➢ If the function is called without the argument, the argument gets its default value.
➢ We can provide a default value to an argument by using the assignment operator (=).
➢ Default arguments allow a function call to pass less parameters than the number of
parameters in the function definition. (no.of parameters in function call and function
header need not be same)
53.Keyword arguments
Example:
54.Variable-length Arguments in python?

1. In some cases we cannot exactly tell how many parameters are needed in a
function definition. In such cases we can use variable length arguments.

2. Variable length arguments allows to pass random number of arguments in a


function call.

3. While creating a variable-length argument, the argument name must be preceded


with *symbol.
Points to remember when working with variable-length arguments:
★ The random arguments passed to the function forms a tuple.
★ A for loop can be used to iterate over and access the elements in the
variable-length argument.
★ A variable-length argument should be at the end of the parameters list in the
function definition.
Example:
55. Difference between Scope and Lifetime?

Variables in a program has two things:

● Scope: Parts of the program in which it is accessible.


● Lifetime: How long a variable stays in the memory.
56. Difference between Local and Global Variables?
57. What is lambda and it's function in programming
Anonymous Functions or LAMBDA Functions:
➔ Functions that don’t have any name are known as lambda or anonymous functions.
➔ Lambda functions are created using the keyword lambda.
➔ Lambda functions are one line functions that can be created and used anywhere a
function is required.
Syntax:lambda arguments-list : expression
Eg:
power = lambda x : x*x*x
print(power(3)) #output:27
Lambda function:
58. What is recursion?
In Python, it’s also possible for a function to call itself.
➔ A function that calls itself is said to be recursive, and the technique of
employing a recursive function is called recursion.
➔ Recursion is another way to repeat code in our programs.
A recursive functions should contain two major parts:
1. base condition part: A condition which terminates recursion and returns the
result.
2. recursive part: Code which calls the function itself with reduced data or
information.
59.What is namespace in python ?

➢ A namespace is a logical collection of names.

➢ Namespaces are used to eliminate name collisions.

➢ Python does not allow programmers to create multiple identifiers with same name.

➢ But, in some case we need identifiers having the same name.


For example, consider two modules module1 and module have the same function sample() as
follows:

Note: When we import both modules into same program and try
to refer sample(), error will be generated:
To avoid the error, we have to use fully qualified name as follows:

Here each module has its own namespace


Basic OOPs Interview Questions
60. What is Object Oriented Programming?

● Object-Oriented Programming(OOPs) is a type of programming that is

based on objects rather than just functions and procedures.

● Individual objects are grouped into classes.

● OOPs implements real-world entities like inheritance, polymorphism,

hiding, etc into programming. It also allows binding data and code

together.
61. Why we use OOPs?

★ OOPs allows clarity in programming thereby allowing simplicity in


solving complex problems
★ Code can be reused through inheritance thereby reducing
redundancy
★ Data and code are bound together by encapsulation
★ OOPs allows data hiding, therefore, private data is kept
confidential
★ Problems can be divided into different parts making it simple to
solve
★ The concept of polymorphism gives flexibility to the program by
allowing the entities to have multiple forms
62. What is Object ? What is Class?
Object Class

An object is a real-world entity which is A class is a prototype that consists of


the basic unit of OOPs. objects in different states and with
different behaviors.
for example chair, cat, dog, etc.
Different objects have different states It has a number of methods that are
or attributes, and behaviors. common the objects present within that
class.
63. What is the difference between a class and a structure?
structure Class

A structure is basically a user-defined Class is User-defined blueprint from


collection of variables which are of which objects are created. It consists of
different data types.. methods or set of instructions that are
to be performed on the objects
64.What are the main features of OOPs?

★ Inheritance
★ Encapsulation
★ Polymorphism
★ Data Abstraction
65. Difference between Procedural programming and OOPs?
Procedural Programming Object-oriented programming
-It is based on functions. -It is based on real-world objects.
-It shows the data to the entire program. -It encapsulates the data.
-It does not have scope for code reuse. -It provides more scope of code reuse.
-It follows a the concept of top-down -It follows a bottom-up programming
programming. paradigm.
-Nature of the language is complicated. -It is less complicated in nature, so it is
easier to modify, extend and maintain
-It is hard to modify, extend and
maintain the code
66. What is inheritance?

● Inheritance is a feature of OOPs which allows classes inherit common


properties from other classes.
● It specifies that the child object acquires all the properties and behaviors
of the parent object.
● For example, if there is a class such as ‘vehicle’, other classes like ‘car’,
‘bike’, etc can inherit common properties from the vehicle class.
● This property helps you get rid of redundant code thereby reducing the
overall size of the code.
67.What are the different types of inheritance?

★ Single inheritance

★ Multiple inheritance

★ Multilevel inheritance

★ Hierarchical inheritance

★ Hybrid inheritance
68.What is polymorphism?

➔ Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape.
➔ By polymorphism, we understand that one task can be performed in different
ways.
➔ For example - you have a class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in a sense and depends on
the animal.
➔ So, the abstract "animal" concept does not actually "speak", but specific animals
(like dogs and cats) have a concrete implementation of the action "speak".
69.What is Encapsulation?
★ Encapsulation is also an essential aspect of object-oriented
programming.
★ It is used to restrict access to methods and variables.
★ In encapsulation, code and data are wrapped together within a
single unit from being modified by accident.
70.What is Data Abstraction?

❏ Data abstraction and encapsulation both are often used as synonyms.


❏ Both are nearly synonyms because data abstraction is achieved through
encapsulation.
❏ Abstraction is used to hide internal details and show only
functionalities.
❏ Abstracting something means to give names to things so that the name
captures the core of what a function or a whole program does.
71.Differentiate between data abstraction and encapsulation.
72. What are ‘access specifiers’?
● Access specifiers or access modifiers are keywords that determine the
accessibility of methods, classes, etc in OOPs.
● These access specifiers allow the implementation of encapsulation.
● The most common access specifiers are public, private and protected.
However, there are a few more which are specific to the programming
languages.
73.What is the difference between public, private and protected
access modifiers?

You might also like