Basic Python Interview Questions Flashcards

1
Q

What is Python?

A
  • Python is a high-level, interpreted, interactive, and object-oriented scripting language. It uses English keywords frequently. Whereas other languages use punctuation, Python has fewer syntactic constructions.
  • Python is designed to be highly readable and compatible with different platforms such as Mac, Windows, Linux, Raspberry Pi, etc.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Python is an interpreted language. Explain.

A

An interpreted language is any programming language where the source code is run through an interpreter which then reads statements line by line, “interpreting” the code into something the machine can understand on the fly.

This is opposed to compiled languages which must have their code parsed through a compiler that converts the source code into machine code before it can actually be run on a machine.

Programs written in Python run directly from the source code, with no intermediary compilation step.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between lists and tuples?

A

Lists

  • Lists are mutable, i.e., they can be edited
  • Lists are usually slower than tuples
  • Lists consume a lot of memory
  • Lists are less reliable in terms of errors as unexpected changes are more likely to occur
  • Lists consist of many built-in functions.
  • Syntax:

list_1 = [10, ‘Intellipaat’, 20]

Tuples

  • Tuples are immutable (they are lists that cannot be edited)
  • Tuples are faster than lists
  • Tuples consume less memory when compared to lists
  • Tuples are more reliable as it is hard for any unexpected change to occur
  • Tuples do not consist of any built-in functions.
  • Syntax:

tup_1 = (10, ‘Intellipaat’ , 20)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is pep 8?

A

PEP in Python stands for Python Enhancement Proposal. It is a set of rules that specify how to write and design Python code for maximum readability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are the Key features of Python?

A
  • Python is an interpreted language, so it doesn’t need to be compiled before execution, unlike languages such as C.
  • Python is dynamically typed, so there is no need to declare a variable with the data type. Python Interpreter will identify the data type on the basis of the value of the variable.

For example, in Python, the following code line will run without any error:

a = 100 a = “Intellipaat”

  • Python follows an object-oriented programming paradigm with the exception of having access specifiers. Other than access specifiers (public and private keywords), Python has classes, inheritance, and all other usual OOPs concepts.
  • Python is a cross-platform language, i.e., a Python program written on a Windows system will also run on a Linux system with little or no modifications at all.
  • Python is literally a general-purpose language, i.e., Python finds its way in various domains such as web application development, automation, Data Science, Machine Learning, and more.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How is Memory managed in Python?

A
  • Memory in Python is managed by Python private heap space. All Python objects and data structures are located in a private heap. This private heap is taken care of by Python Interpreter itself, and a programmer doesn’t have access to this private heap.
  • Python memory manager takes care of the allocation of Python private heap space.
  • Memory for Python private heap space is made available by Python’s in-built garbage collector, which recycles and frees up all the unused memory.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is PYTHONPATH?

A

PYTHONPATH has a role similar to PATH. This variable tells 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 Python Installer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are Python Modules?

A

Files containing Python codes are referred to as Python Modules. This code can either be classes, functions, or variables and saves the programmer time by providing the predefined functionalities when needed. It is a file with “.py” extension containing an executable code.

Commonly used built modules are listed below:

  • os
  • sys
  • data time
  • math
  • random
  • JSON
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are python namespaces?

A

A Python namespace ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with ‘name as key’ mapped to its respective ‘object as value’.

Let’s explore some examples of namespaces:

  • Local Namespace consists of local names inside a function. It is temporarily created for a function call and gets cleared once the function returns.
  • Enclosed Namespace: When a function is defined inside a function, it creates an enclosed namespace. Its lifecycle is the same as the local namespace.
  • Global Namespace: Belongs to the python script or the current module. The global namespace for a module is created when the module definition is read. Generally, module namespaces also last until the interpreter quits.
  • Built-in Namespace consists of built-in functions of core Python and dedicated built-in names for various types of exceptions. It is created when the Python interpreter starts up and is never deleted.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain Inheritance in Python with an example?

A

Inheritance allows us to define a class that inherits all the methods and properties from another class.

Inheritance provides the code reusability feature.

Parent class is the class being inherited from, also called base class or super class.

Child class is the class that inherits from another class, also called derived class.

The following types of inheritance are supported in Python:

  • Single inheritance: When a class inherits only one superclass
  • Multiple inheritance: When a class inherits multiple superclasses
  • Multilevel inheritance: When a class inherits a superclass, and then another class inherits this derived class forming a ‘parent, child, and grandchild’ class structure
  • Hierarchical inheritance: When one superclass is inherited by multiple derived classes
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is scope resolution?

A

The scope of an object name is the region of a program in which that name has meaning.

Scope resolution is required when a variable is used to determine where should its value come from. The interpreter determines this at runtime based on where the name definition occurs and where in the code the name is referenced. Scope resolution in Python follows the LEGB rule.

L, Local — Names assigned in any way within a function (or lambda), and not declared global in that function.

E, Enclosing-function locals — Name in the local scope of any and all statically enclosing functions(or lambdas), from inner to outer.

G, Global (module) — Names assigned at the top-level of a module file, or by executing a global statement in a def within the file.

B, Built-in (Python) — Names preassigned in the built-in names module : open, range,SyntaxError, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a dictionary in Python?

A

Python dictionary is one of the supported data types in Python. It is an unordered collection of elements. The elements in dictionaries are stored as key-value pairs. Dictionaries are indexed by keys.

For example, below we have a dictionary named ‘dict’. It contains two keys, Country and Capital, along with their corresponding values, India and New Delhi.

Syntax:

dict={‘Country’:’India’,’Capital’:’New Delhi’, }

Output: Country: India, Capital: New Delhi

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are functions in Python?

A

A function is a block of code which is executed only when a call is made to the function.

The def keyword is used to define a particular function as shown below:

def function():

print(“Hi, Welcome to Intellipaat”)

function(); # call to the function

Output:
Hi, Welcome to Intellipaat

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is __init__ in Python?

A

Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python classes. The __init__ method is called automatically whenever a new object is initiated. This method allocates memory to the new object as soon as it is created. This method can also be used to initialize variables.

Syntax

(for defining the __init__ method):

class Human:

init method or constructor

def __init__(self, age):

self.age = age

Sample Method

def say(self):

print(‘Hello, my age is’, self.age)

h= Human(22)

h.say()

Output:

Hello, my age is 22

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the common built-in data types in Python?

A

Python supports the below-mentioned built-in data types:

Immutable data types:

  • Number
  • String
  • Tuple

Mutable data types:

  • List
  • Dictionary
  • Set
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What are local variables and global variables in Python?

A

Local variable: Any variable declared inside a function is known as Local variable and it’s accessibility remains inside that function only.

Global Variable: Any variable declared outside the function is known as Global variable and it can be easily accessible by any function present throughout the program.

17
Q

What is type conversion in Python?

A

Python provides you with a much-needed functionality of converting one form of data type into the needed one and this is known as type conversion.

Type Conversion is classified into types:

  1. Implicit Type Conversion: In this form of type conversion python interpreter helps in automatically converting the data type into another data type without any User involvement.
  2. Explicit Type Conversion: In this form of Type conversion the data type inn changed into a required type by the user.

Various Functions of explicit conversion are shown below:

int() – function converts any data type into integer.

float() – function converts any data type into float.

ord() – function returns an integer representing the Unicode character

hex() – function converts integers to hexadecimal strings.

oct() – function converts integer to octal strings.

tuple() – function convert to a tuple.

set() – function returns the type after converting to set.

list() – function converts any data type to a list type.

dict() – function is used to convert a tuple of order (key,value) into a dictionary.

str() – function used to convert integer into a string.

complex(real,imag) – function used to convert real numbers to complex(real,imag) numbers.

18
Q

How to install Python on Windows and set a path variable?

A

For installing Python on Windows, follow the steps shown below:

Click on this link for installing the python:

Download Python

  • After that, install it on your PC by looking for the location where PYTHON has been installed on your PC by executing the following command on command prompt;

cmd python.

  • Visit advanced system settings and after that add a new variable and name it as PYTHON_NAME and paste the path that has been copied.
  • Search for the path variable -> select its value and then select ‘edit’.
  • Add a semicolon at the end of the value if it’s not present and then type %PYTHON_HOME%
19
Q

What is the difference between Python Arrays and lists?

A

List:

  • Consists of elements belonging to different data types
  • No need to import a module for list declaration
  • Can be nested to have different type of elements
  • Recommended to use for shorter sequence of data items
  • More flexible to allow easy modification (addition or deletion) of data
  • Consumes large memory for the addition of elements
  • Can be printed entirely without using looping
  • Syntax:
    list = [1,”Hello”,[‘a’,’e’]]

Array:

  • Consists of only those elements having the same data type
  • Need to explicitly import a module for array declaration
  • Must have all nested elements of the same size
  • Recommended to use for longer sequence of data items
  • Less flexible since addition or deletion has to be done element-wise
  • Comparatively more compact in memory size while inserting elements
  • A loop has to be defined to print or access the components
  • Syntax:
    import array
    array_demo = array.array(‘i’, [1, 2, 3])
    (array as integer type)
20
Q

Is python case sensitive?

A

Yes, Python is a case sensitive language. This means that Function and function both are different in pythons like SQL and Pascal.

21
Q

What does [::-1] do?

A

[::-1] ,this is an example of slice notation and helps to reverse the sequence with the help of indexing.

[Start,stop,step count]

Let’s understand with an example of an array:

import array as arr

Array_d=arr.array(‘i’,[1,2,3,4,5])

Array_d[::-1] #reverse the array or sequence

Output: 5,4,3,2,1

22
Q

What are Python packages?

A

A Python package refers to the collection of different sub-packages and modules based on the similarities of the function.

23
Q

What are decorators in Python?

A

In Python, decorators are necessary functions that help add functionality to an existing function without changing the structure of the function at all. These are represented by @decorator_name in Python and are called in a bottom-up format.

Let’s have a look how it works:

def decorator_lowercase(function): # defining python

decorator def wrapper():

func = function()

input_lowercase = func.lower()

return input_lowercase

return wrapper @decorator_lowercase ##calling decoractor

def intro(): #Normal function

return ‘Hello,I AM SAM’

hello()

24
Q

Is indentation required in Python?

A

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.

25
Q

How does break, continue, and pass work?

A

These statements help to change the phase of execution from the normal flow that is why they are termed loop control statements.

Python break: This statement helps terminate the loop or the statement and pass the control to the next statement.

Python continue: This statement helps force the execution of the next iteration when a specific condition meets, instead of terminating it.

Python pass: This statement helps write the code syntactically and wants to skip the execution. It is also considered a null operation as nothing happens when you execute the pass statement.

26
Q

How can you randomize the items of a list in place in Python?

A

This can be easily achieved by using the Shuffle() function from the random library as shown below:

from random import shuffle

List = [‘He’, ‘Loves’, ‘To’, ‘Code’, ‘In’, ‘Python’]

shuffle(List)

print(List)

Output:

[‘Loves’,’He’ ,’To ,’In’, ‘Python’,’Code’]

27
Q

How to comment with multiple lines in Python?

A

There are two ways to add multiple lines comment in python:

  1. All the line should be prefixed by #.
  2. Use docstring syntax (triple quotes: “”” text “”” )
    • When using docstring method proper indentation matters and will cause an indention error if not followed.
28
Q

What type of language is python? Programming or scripting?

A

Generally, Python is an all purpose Programming Language ,in addition to that Python is also Capable to perform scripting.

29
Q

What are negative indexes and why are they used?

A

To access an element from ordered sequences, we simply use the index of the element, which is the position number of that particular element. The index usually starts from 0, i.e., the first element has index 0, the second has 1, and so on.

When we use the index to access elements from the end of a list, it’s called reverse indexing. In reverse indexing, the indexing of elements starts from the last element with the index number ‘−1’. The second last element has index ‘−2’, and so on. These indexes used in reverse indexing are called negative indexes.