Python Interview QnA

You might also like

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

Python

Interview Question and Answer


1) What is Python and what are its key features?

y
Python is a high-level, interpreted programming language that was first

m
released in 1991 by Guido van Rossum. It is popular for its simplicity and ease of
use, as well as its extensive libraries and frameworks.

de
Some of the key features of Python are:
1. Simple and easy to learn syntax: Python has a simple, intuitive syntax that
makes it easy to read and write code. Its code is often shorter than other

ca
programming languages, which makes it easier to maintain and debug.
2. Interpreted: Python is an interpreted language, which means that code can
be executed directly without the need for a compiler. This makes it easier
gA
to test and debug code, as well as run code on multiple platforms without
having to worry about platform-specific issues.
3. Dynamic typing: Python is dynamically typed, meaning that variable types
tin

are determined at runtime rather than at compile-time. This allows for


more flexibility in programming, as well as more efficient use of memory.
4. Large standard library: Python comes with a large standard library that
provides support for many common programming tasks, such as web
es

development, data analysis, and scientific computing. This library is also


constantly evolving, with new modules and packages being added all the
eT

time.
5. Object-oriented programming support: Python supports object-oriented
programming (OOP), which allows developers to create reusable code and
build more complex applications. OOP is an important programming
Th

paradigm that enables developers to create code that is easier to maintain


and scale.
6. Cross-platform: Python code can be run on multiple platforms, including
Windows, Linux, and macOS, without the need for modification. This
makes it a popular choice for cross-platform development, as well as for
scripting and automation tasks.
7. Community and ecosystem: Python has a large and active community of
developers who contribute to its development and support its growth. This
has led to the creation of a vast ecosystem of libraries, frameworks, and
tools that make Python an even more powerful and versatile language.

2) What are the different data types in Python?


Python has several built-in data types, including:
1. Numbers: Python supports integers, floating-point numbers, and complex
numbers. These data types can be used for arithmetic operations, such as
addition, subtraction, multiplication, and division.
2. Strings: Strings are used to represent text data in Python. They can be

y
enclosed in single or double quotes, and can be manipulated using various

m
string methods.
3. Lists: Lists are used to store a collection of values, which can be of
different data types. They are mutable, which means that their contents

de
can be changed.
4. Tuples: Tuples are similar to lists, but they are immutable, which means
that their contents cannot be changed once they are created.
5.

6. ca
Sets: Sets are used to store a collection of unique values. They are
mutable and unordered, which means that their elements are not indexed.
Dictionaries: Dictionaries are used to store key-value pairs. They are
gA
mutable and unordered, and can be used to efficiently store and retrieve
data based on keys.
7. Booleans: Booleans are used to represent logical values, such as True or
False. They are often used in conditional statements and loops to control
tin

program flow.
8. None: None is a special value in Python that represents the absence of a
value. It is often used as a placeholder or to indicate that a variable has not
es

been assigned a value yet.

3) What is PEP 8 and why is it important?


eT

PEP 8 is a style guide for writing Python code. It was created to promote
consistency and readability in Python code, making it easier for developers to
understand and maintain code written by others. PEP stands for Python
Th

Enhancement Proposal, and PEP 8 is one of many proposals that have been
submitted to improve the Python language and its ecosystem.
PEP 8 provides guidelines for various aspects of Python code, including:

● Indentation and whitespace


● Naming conventions for variables, functions, and classes
● Function and class definitions
● Comments and documentation
● Import statements
Following the guidelines in PEP 8 can make code more readable and
easier to maintain. Consistency in coding style makes it easier for developers to
understand each other's code, which is particularly important in collaborative
projects.
In addition, many code editors and tools have built-in support for PEP 8
guidelines, which can help automate and enforce coding standards. Adhering to
PEP 8 can also make it easier to write automated tests and ensure code quality.
Overall, PEP 8 is an important resource for Python developers to improve

y
the readability, consistency, and maintainability of their code.

m
4) How do you comment a Python code?
Python provides two ways to add comments to code:

de
# Single-line comments: To add a comment that spans a single line, use the
hash symbol (#) followed by the text of the comment. For example:

ca
# This is a single-line comment
print("Hello, world!") # This line also has a comment
gA
In this example, the first line is a single-line comment, and the second line
includes code and a comment.
tin

# Multi-line comments: To add a comment that spans multiple lines, you can use
a string literal that is not assigned to a variable. For example:
"""
es

This is a multi-line comment.


It can span multiple lines.
"""
eT

print("Hello, world!")

In this example, the multi-line comment is enclosed in triple quotes, which


Th

creates a string literal that is not assigned to a variable. The comment spans
multiple lines and is ignored by the Python interpreter.
It's important to note that comments should be used sparingly and only when
necessary to explain the code or provide additional context. Overuse of
comments can make code harder to read and maintain, and can indicate that the
code itself needs to be improved.
5) What is the difference between single and double
quotes in Python?
In Python (and in many programming languages), both single and double
quotes are used to define string literals, which are sequences of characters
enclosed in quotes.
The main difference between single and double quotes in Python is that
they can be used interchangeably to define string literals. However, if a string
literal contains a quote character (either a single quote or a double quote), the

y
opposite type of quote can be used to define the string, avoiding the need for
escape characters.

m
For example, the following two statements are equivalent in Python:
greeting = 'Hello, world!'

de
greeting = "Hello, world!"

In the second statement, double quotes are used instead of single quotes to

ca
define the string literal.

However, if the string literal contains a quote character, using the opposite type of
gA
quote can simplify the code:
message = "He said, 'I am going to the store.'"
message = 'He said, "I am going to the store."'
tin

In the first statement, single quotes are used to define the string literal,
but double quotes are used within the string to represent the quote spoken by
someone. In the second statement, double quotes are used to define the string
es

literal, but single quotes are used within the string to represent the quote spoken
by someone. This avoids the need to escape the quote character with a
backslash.
eT

6) What is a variable in Python?


In Python, a variable is a name that is used to refer to a value stored in memory. It
Th

is like a label that refers to a particular object in the computer's memory.

When you assign a value to a variable, Python creates the object representing
that value and stores it in memory, and the variable refers to that object. You can
then use the variable name to access or manipulate the value stored in the
memory location associated with the variable.
In Python, you can assign a value to a variable using the equal sign (=) operator.
Here's an example:
x=5

In this example, the variable x is assigned the value 5. Python creates an integer
object with the value of 5 and stores it in memory. The variable x then refers to
that memory location.

Variables in Python can store different types of data, including integers,

y
floating-point numbers, strings, booleans, and more complex data types like lists,

m
dictionaries, and objects. You don't need to specify the type of a variable when
you create it, as Python infers the type based on the value you assign to it.

de
You can also change the value of a variable by assigning a new value to it. For
example:
x=5

ca
x = 10

In this example, the variable x is first assigned the value 5, and then the value of x
gA
is changed to 10.

7) How do you assign a value to a variable in Python?


You can assign a value to a variable in Python by using the assignment operator,
tin

which is the equal sign (=). The general syntax for variable assignment is:

variable_name = value
es

Here, variable_name is the name you choose for your variable, and value is the
value you want to assign to it.
eT

For example, let's say you want to create a variable called my_var and assign it
the value 42. You can do this as follows:
Th

my_var = 42
Now the variable my_var refers to the integer object with the value 42 in memory.

You can also assign different types of values to variables in Python. For example,
you can assign a string value to a variable as follows:
my_string = "Hello, World!"

Or you can assign a boolean value to a variable:


my_bool = True
Python will automatically infer the data type of the value you assign to a variable
and store it accordingly.

8) What is a data type conversion in Python?


In Python, data type conversion is the process of changing the data type of a
value from one type to another. This can be useful when you need to perform

y
operations that are only valid for certain data types, or when you need to pass a

m
value of one type to a function that expects a different type.

Python provides several built-in functions that allow you to convert between data

de
types. Here are some of the most common ones:
● int() converts a value to an integer data type.
● float() converts a value to a floating-point data type.

ca
● str() converts a value to a string data type.
● bool() converts a value to a boolean data type.
gA
Here are some examples of how to use these functions:
# Converting a string to an integer
x = "10"
y = int(x)
tin

print(y) # Output: 10

# Converting a float to an integer


es

x = 3.14
y = int(x)
print(y) # Output: 3
eT

# Converting an integer to a string


x = 42
Th

y = str(x)
print(y) # Output: "42"

# Converting a boolean to a string


x = True
y = str(x)
print(y) # Output: "True"
Note that not all data type conversions are valid in Python. For example, you
cannot convert a string that contains non-numeric characters to an integer using
the int() function. In such cases, you may need to use more advanced techniques
like regular expressions to extract the numeric part of the string before
converting it to an integer.

9) What is the difference between an integer and a float


in Python?

y
In Python (and in many programming languages), integers and floats are different
types of numeric data.

m
An integer is a whole number that can be positive, negative, or zero. Integers are
represented in Python using the int data type. Here are some examples of

de
integers:
x=5
y = -10
z=0

ca
A float is a number with a decimal point that can also be positive, negative, or
zero. Floats are represented in Python using the float data type. Here are some
gA
examples of floats:
x = 3.14
y = -2.5
tin

z = 0.0

The main difference between integers and floats is that floats can represent
es

fractional numbers and have a larger range than integers. In Python, floats use
more memory than integers and are slower to perform arithmetic operations on
than integers.
eT

Here's an example of how to perform arithmetic operations on integers and floats


in Python:

# Integer arithmetic
Th

x = 10
y=3
z = x + y # z = 13
z=x-y #z=7
z = x * y # z = 30
z = x // y # z = 3 (integer division)
z = x % y # z = 1 (remainder)
# Float arithmetic
x = 3.14
y = 1.5
z = x + y # z = 4.64
z = x - y # z = 1.64
z = x * y # z = 4.71
z = x / y # z = 2.0933...

Note that when performing division on integers in Python using the forward slash

y
(/) operator, the result is always a float, even if the division would yield an integer

m
result. To perform integer division and get an integer result, you can use the
double forward slash (//) operator.

de
10) What is a string in Python?
In Python, a string is a sequence of characters. Strings are used to represent
textual data and are represented in Python using the str data type. Strings are

ca
enclosed in either single quotes ('...') or double quotes ("...").

Here are some examples of strings:


gA
name = 'Alice'
message = "Hello, World!"
empty_string = ''
tin

Strings can contain any Unicode character, including letters, digits, punctuation,
and whitespace. You can access individual characters in a string using indexing
and slicing operations. For example:
es

my_string = "Hello, World!"


print(my_string[0]) # Output: "H"
print(my_string[7]) # Output: "W"
eT

print(my_string[0:5]) # Output: "Hello"

Strings are immutable, which means that once you create a string, you cannot
Th

change its contents. However, you can create new strings by concatenating or
formatting existing strings.
Here are some examples of string concatenation and formatting:
first_name = "Alice"
last_name = "Smith"

# String concatenation
full_name = first_name + " " + last_name
print(full_name) # Output: "Alice Smith"
# String formatting
age = 30
message = "My name is {} {} and I am {} years old".format(first_name, last_name,
age)
print(message) # Output: "My name is Alice Smith and I am 30 years old"

In Python 3.6 and later versions, you can also use f-strings to format strings.
Here's an example:

y
first_name = "Alice"

m
last_name = "Smith"
age = 30

de
message = f"My name is {first_name} {last_name} and I am {age} years old"
print(message) # Output: "My name is Alice Smith and I am 30 years old"

11) How do you concatenate two strings in Python?

ca
In Python, you can concatenate two strings using the + operator or the join()
method. Here are examples of both methods:
gA
Using the + operator:

string1 = "Hello"
string2 = "world"
tin

result = string1 + " " + string2


print(result) # Output: "Hello world"
es

In the example above, the + operator is used to concatenate the two strings
string1 and string2 with a space in between.
Using the join() method:
eT

string1 = "Hello"
string2 = "world"
Th

result = " ".join([string1, string2])


print(result) # Output: "Hello world"

In the example above, the join() method is used to concatenate the two strings
string1 and string2 with a space in between. The join() method takes a list of
strings as an argument and joins them together with the string on which it is
called as a separator.
12) How do you format a string in Python?
In Python, you can format a string using the str.format() method or f-strings
(formatted string literals) introduced in Python 3.6.

# Using the str.format() method:


The str.format() method replaces the placeholders in a string with the
specified values. Here's an example:
# Using positional arguments
name = "Alice"

y
age = 25

m
print("My name is {} and I'm {} years old.".format(name, age))
# Output: My name is Alice and I'm 25 years old.

de
# Using keyword arguments
print("My name is {name} and I'm {age} years old.".format(name="Bob", age=30))
# Output: My name is Bob and I'm 30 years old.

ca
# Using f-strings:
f-strings are a more concise way of formatting strings introduced in Python 3.6.
gA
They allow you to embed expressions inside string literals, using curly braces {}
to indicate the expression. Here's an example:
# Using f-strings
name = "Charlie"
tin

age = 35
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Charlie and I'm 35 years old.
es

Both methods are widely used in Python, and you can choose the one that suits
your needs and coding style.
eT

13) What is an input function in Python?


In Python, input() is a built-in function that allows the user to input data from the
Th

keyboard as a string. The function takes a single argument, which is a string that
prompts the user for input. Here's an example:

name = input("Please enter your name: ")


print("Hello, " + name + "!")

In this example, the input() function displays the prompt "Please enter your
name:" on the console and waits for the user to enter a string. When the user
presses the Enter key, the input() function reads the string entered by the user
and returns it as a value. The program then assigns this value to the variable
name and prints a greeting message.

Note that the input() function always returns a string value, even if the user enters
a number or some other type of data. If you want to convert the input to a
different data type, such as an integer or a floating-point number, you can use the
appropriate conversion function (e.g. int() or float()) to convert the string to the
desired type.

y
14) How do you print output in Python?
In Python, you can print output to the console or terminal using the print()

m
function. The print() function takes one or more arguments, separated by
commas, and prints them to the console as a string. Here are some example

de
# Printing a string
print("Hello, world!")

ca
# Output: Hello, world!

# Printing variables
gA
name = "Alice"
age = 25
print("My name is", name, "and I'm", age, "years old.")
# Output: My name is Alice and I'm 25 years old.
tin

# Printing expressions
x = 10
es

y = 20
print("The sum of", x, "and", y, "is", x + y)
# Output: The sum of 10 and 20 is 30.
eT

# Printing formatted strings using f-strings


name = "Bob"
Th

age = 30
print(f"My name is {name} and I'm {age} years old.")
# Output: My name is Bob and I'm 30 years old.

You can also use special characters like \n for a new line, \t for a tab, and \\ to
print a backslash.

print("This is a\ttabbed text.")


# Output: This is a tabbed text.
print("This is a\nmulti-line\nstring.")
# Output:
# This is a
# multi-line
# string.

print("This is a backslash: \\")


# Output: This is a backslash: \

y
m
These are just a few examples of what you can do with the print() function in
Python. The print() function is a powerful tool that allows you to display
information to the user or to the console for debugging purposes.

de
15) What is a conditional statement in Python?
In Python, a conditional statement is a programming construct that allows you to

ca
execute different blocks of code based on whether a certain condition is true or
false. The most common type of conditional statement is the if statement, which
has the following syntax:
gA
if condition:
# Block of code to execute if the condition is true
else:
tin

# Block of code to execute if the condition is false

Here, condition is an expression that evaluates to either True or False. If the


es

condition is true, the block of code indented under the if statement is executed,
and if it is false, the block of code indented under the else statement is executed.
Optionally, you can also use the elif statement (short for "else if") to test
eT

additional conditions. The syntax for an if statement with elif clauses is as


follows:
Th

if condition1:
# Block of code to execute if condition1 is true
elif condition2:
# Block of code to execute if condition2 is true
else:
# Block of code to execute if neither condition1 nor condition2 is true
Here, condition1 and condition2 are expressions that evaluate to either True or
False. The elif clause is used to test an additional condition if the previous if or
elif clauses have failed.

Conditional statements are powerful tools that allow you to create logic and
decision-making in your code. You can use them to test variables, compare
values, and create complex branching structures in your program.

16) What is an if statement in Python?

y
In Python, an if statement is a conditional statement that allows you to execute a
block of code if a certain condition is true. The basic syntax of an if statement is:

m
if condition:

de
# Block of code to execute if the condition is true

Here, condition is an expression that evaluates to either True or False. If the

ca
condition is true, the block of code indented under the if statement is executed,
and if it is false, the block of code is skipped and the program continues
executing from the next line after the if block.
gA
Optionally, you can also use the else clause to execute a different block of code if
the condition is false. The syntax for an if statement with an else clause is as
follows:
tin

if condition:
# Block of code to execute if the condition is true
else:
es

# Block of code to execute if the condition is false

Here, if the condition is true, the block of code indented under the if statement is
eT

executed, and if it is false, the block of code indented under the else statement is
executed.
Th

Optionally, you can also use the elif statement (short for "else if") to test
additional conditions. The syntax for an if statement with elif clauses is as
follows:
if condition1:
# Block of code to execute if condition1 is true
elif condition2:
# Block of code to execute if condition2 is true
else:
# Block of code to execute if neither condition1 nor condition2 is true
Here, condition1 and condition2 are expressions that evaluate to either True or
False. The elif clause is used to test an additional condition if the previous if or
elif clauses have failed.

Conditional statements are powerful tools that allow you to create logic and
decision-making in your code. You can use them to test variables, compare
values, and create complex branching structures in your program.

y
17) What is a for loop in Python?
In Python, a for loop is a control flow statement that allows you to iterate over a

m
sequence of elements, such as a list, tuple, or string, and perform a set of
instructions for each item in the sequence. The basic syntax of a for loop is:

de
for variable in sequence:
# Block of code to execute for each item in the sequence

ca
Here, variable is a variable that is assigned the value of each item in the
sequence, one at a time, and sequence is the sequence of elements to iterate
gA
over. The block of code indented under the for statement is executed once for
each item in the sequence, with the variable taking on the value of each item in
turn.
For example, to print each item in a list, you could use a for loop like this:
tin

my_list = [1, 2, 3, 4, 5]
for item in my_list:
es

print(item)

In this example, the for loop iterates over the elements in my_list, with the item
eT

variable taking on the value of each element in turn. The print() function is then
called for each item, printing it to the console.
You can also use the built-in range() function to generate a sequence of integers
Th

to iterate over, like this:


for i in range(10):
print(i)

In this example, the for loop iterates over the integers from 0 to 9, with the i
variable taking on the value of each integer in turn. The print() function is then
called for each integer, printing it to the console.
for loops are a fundamental construct in Python programming, and they are used
extensively in many types of programs, from simple scripts to complex
applications.

18) What is a while loop in Python?


A while loop in Python is a type of loop that repeats a block of code while a
certain condition is True. The basic syntax of a while loop in Python is as follows:

while condition:

y
# Code to be repeated while condition is True

m
The condition is a Boolean expression that is evaluated before each iteration of
the loop. If the condition is True, the code inside the loop is executed, and then

de
the condition is evaluated again. This process continues until the condition is
False. Once the condition is False, the loop stops and the program continues
executing from the next statement after the loop.

ca
Here's an example of a simple while loop in Python that prints the numbers from
1 to 5:
gA
i=1
while i <= 5:
print(i)
i=i+1
tin

In this example, the loop starts with i equal to 1. The condition i <= 5 is True, so
the code inside the loop is executed, which prints the value of i (which is 1) and
es

then increments i by 1. The loop then repeats with i equal to 2, and continues
until i is equal to 6, at which point the condition i <= 5 is False and the loop stops.
The output of the above code would be:
eT

1
2
3
Th

4
5

19) How do you break out of a loop in Python?


You can break out of a loop in Python using the break statement. When the break
statement is executed inside a loop, the loop is immediately terminated and the
program continues with the next statement after the loop.
Here's an example of a while loop that counts from 1 to 10, but breaks out of the
loop when the value of the counter variable i is equal to 5:

i=1
while i <= 10:
print(i)
if i == 5:
break
i += 1

y
m
In this example, the if statement checks if the value of i is equal to 5. If it is, the
break statement is executed, which immediately terminates the loop. Otherwise,
the loop continues to the next iteration.

de
The output of the above code would be:
1
2

ca
3
4
5
gA
20) What is a function in Python?
A function in Python is a block of code that performs a specific task and can be
reused throughout a program. It is a self-contained unit of code that takes one or
tin

more inputs, performs some operations on them, and returns one or more
outputs.
es

Functions in Python are defined using the def keyword, followed by the function
name, a set of parentheses containing any parameters (inputs) that the function
takes, and a colon. The function code is then indented and executed when the
eT

function is called. Here's the basic syntax of a function in Python:


def function_name(parameters):
# Function code
Th

return output

The parameters are optional and can be used to pass one or more values to the
function. The function code can perform any task, including calculations, string
operations, file input/output, and more. The return statement is optional and is
used to return one or more values from the function.
Here's an example of a simple function in Python that takes two numbers as
inputs and returns their sum:
def add_numbers(x, y):
sum = x + y
return sum

In this example, the function add_numbers takes two parameters x and y, adds
them together, and returns the sum. The function can be called with any two
numbers as inputs, like this:

result = add_numbers(5, 3)
print(result)

y
m
This would output 8, which is the result of adding 5 and 3 together using the
add_numbers function.
Functions are a powerful feature of Python that allow you to organize your code

de
into reusable units and avoid duplicating code throughout your program.

21) How do you define a function in Python?

ca
To define a function in Python, you use the def keyword followed by the function
name, a set of parentheses that may contain parameters (inputs) to the function,
and a colon. The function body, which contains the code that is executed when
gA
the function is called, is indented beneath the function definition. Here's the basic
syntax for defining a function in Python:

def function_name(parameters):
tin

# function body
return value
es

Here's an example of a function definition that takes two numbers as input,


calculates their product, and returns the result:
eT

def multiply(a, b):


result = a * b
return result
Th

In this example, multiply is the name of the function, and it takes two parameters
a and b. The function body calculates the product of a and b and assigns the
result to a variable called result. Finally, the return statement returns the value of
result as the output of the function.

Once you have defined a function, you can call it from anywhere in your program
by using its name and passing in the appropriate arguments. Here's an example
of calling the multiply function from another part of your program:
# call the multiply function and print the result
result = multiply(4, 5)
print(result)

This would output 20, which is the product of 4 and 5 as calculated by the
multiply function.

22) What is a return statement in Python?


A return statement in Python is used to exit a function and optionally return a

y
value to the caller of the function. When a return statement is executed, the
function is terminated and control is returned to the point where the function was

m
called.

de
Here's the basic syntax of a return statement in Python:
return expression

ca
The expression is optional and can be any valid Python expression. If present, it
specifies the value that the function should return to the caller. If omitted, the
function returns None by default.
gA
Here's an example of a function that uses a return statement to return a value:

def add_numbers(x, y):


sum = x + y
tin

return sum

In this example, the add_numbers function takes two parameters x and y,


es

calculates their sum, and returns the result using the return statement.
You can call the function and store its return value in a variable like this:
result = add_numbers(2, 3)
eT

print(result) # Output: 5

The output of the above code would be 5, which is the result of adding 2 and 3
Th

together using the add_numbers function.

Return statements are an important feature of functions in Python, as they allow


you to return values from functions to other parts of your program. They can also
be used to exit a function early if a certain condition is met, which c
an be useful for improving the efficiency of your code.
23) What is a default argument in Python?
A default argument is a value that can be assigned to a parameter in a Python
function definition, which is used when the argument is not provided by the caller
of the function.
When a function is called with fewer arguments than the number of parameters
defined in the function signature, the default values are used for any parameters
that are not explicitly passed in the function call.
Here is an example of a function with a default argument:
def greet(name="Guest"):

y
print("Hello, " + name + "!")

m
In this example, the name parameter has a default value of "Guest". If no
argument is passed to the greet() function, it will use "Guest" as the value of

de
name.

# Call the function without argument

ca
greet() # Output: Hello, Guest!

# Call the function with argument


gA
greet("John") # Output: Hello, John!

Note that default arguments must come after non-default arguments in the
function signature. For example, this is a valid function definition:
tin

def foo(a, b, c=0, d=1):


# do something
es

Here, a and b are required parameters, while c and d are optional parameters with
default values of 0 and 1, respectively.
eT

24) What is a variable scope in Python?


In Python, variable scope refers to the region of the program where the variable is
Th

accessible. The scope of a variable determines the places where the variable can
be accessed or modified.
In Python, there are two types of variable scopes:

1. Global scope: A variable declared outside of any function or class has a


global scope. Global variables are accessible from any part of the program,
including functions and classes.
2. Local scope: A variable declared inside a function or block has a local
scope. Local variables are only accessible within the function or block in
which they are defined.

For example, consider the following code:


x = 10 # global variable
def my_func():
y = 5 # local variable
print(x) # accessing global variable

y
print(y) # accessing local variable

m
my_func()
print(x) # accessing global variable outside of function

de
In this example, x is a global variable and y is a local variable. The function
my_func has access to both the global variable x and the local variable y.

ca
However, x can also be accessed outside of the function, as it has a global
scope.

25) What is a global keyword in Python?


gA
In Python, the global keyword is used to indicate that a variable defined inside a
function should be treated as a global variable, rather than a local variable. This
means that the variable can be accessed or modified from anywhere in the
tin

program, not just within the function where it is defined.


Consider the following example:
x = 10 # global variable
es

def my_func():
global x
eT

x = 5 # changing the value of global variable x


print(x)
Th

my_func() # prints 5
print(x) # prints 5
In this example, the global keyword is used to indicate that the variable x inside
the function my_func should refer to the global variable x, rather than a new local
variable. Therefore, when x is assigned the value of 5 inside the function, it
changes the value of the global variable x to 5.

Note that using the global keyword should be done with caution, as it can lead to
unexpected behavior and make the code harder to read and maintain. It is
generally considered better practice to avoid using global variables and instead
pass variables between functions as arguments or return values.

26) What is a list in Python?


In Python, a list is a collection of values that are ordered and mutable. A list is
created by enclosing a comma-separated sequence of values in square brackets
[ ].
For example, the following code creates a list of integers:
my_list = [1, 2, 3, 4, 5]

y
Lists can contain elements of any data type, including other lists:

m
mixed_list = [1, 'two', 3.0, [4, 5, 6]]

de
You can access elements of a list using indexing, starting from 0:
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # prints 1

ca
print(my_list[2]) # prints 3

Lists are mutable, which means that you can modify their contents by assigning
gA
new values to specific indexes or using built-in methods, such as append(),
insert(), remove(), pop(), and sort().

my_list = [1, 2, 3, 4, 5]
tin

my_list[1] = 6 # replaces 2 with 6


print(my_list) # prints [1, 6, 3, 4, 5]
es

my_list.append(6) # adds 6 to the end of the list


print(my_list) # prints [1, 6, 3, 4, 5, 6]
eT

Lists are commonly used in Python for storing and manipulating collections of
data, such as sequences of numbers or strings.

27) How do you access elements in a list in Python?


Th

In Python, you can access elements in a list by using indexing, which allows you
to specify the position of the element you want to access.
The indexing of a list starts at 0 for the first element, and goes up to the length of
the list minus one for the last element.

Here are some examples of how to access elements in a list:


my_list = ['apple', 'banana', 'cherry', 'date']
# Access the first element (index 0) in the list
print(my_list[0]) # Output: 'apple'

# Access the third element (index 2) in the list


print(my_list[2]) # Output: 'cherry'

# Access the last element (index -1) in the list


print(my_list[-1]) # Output: 'date'

y
You can also use slicing to access a range of elements in a list:

m
my_list = ['apple', 'banana', 'cherry', 'date']

# Access a slice of the list from the second element (index 1) up to but not

de
including the last element (index 3)
print(my_list[1:3]) # Output: ['banana', 'cherry']

ca
# Access a slice of the list from the third element (index 2) to the end of the list
print(my_list[2:]) # Output: ['cherry', 'date']
gA
# Access a slice of the list from the beginning of the list up to but not including
the third element (index 2)
print(my_list[:2]) # Output: ['apple', 'banana']
tin

You can also modify the elements in a list by assigning new values to specific
indexes:
my_list = ['apple', 'banana', 'cherry', 'date']
es

# Replace the second element (index 1) in the list with 'grapefruit'


my_list[1] = 'grapefruit'
eT

print(my_list) # Output: ['apple', 'grapefruit', 'cherry', 'date']

28) How do you add an element to a list in Python?


Th

To add an element to a list in Python, you can use the append() method. Here's
an example:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)

This will output:


[1, 2, 3, 4]
You can also use the insert() method to add an element to a specific index in the
list. Here's an example:
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)

This will output:


[1, 4, 2, 3]

y
m
In this example, the number 4 is added to the index position 1, which causes the
other elements to shift over.

de
29) How do you remove an element from a list in Python?
To remove an element from a list in Python, you can use the remove() method.
Here's an example:

ca
my_list = [1, 2, 3, 4]
my_list.remove(3)
gA
print(my_list)

This will output:


[1, 2, 4]
tin

In this example, the remove() method is used to remove the number 3 from the
list.
es

If you know the index of the element you want to remove, you can use the pop()
method. Here's an example:
my_list = [1, 2, 3, 4]
eT

my_list.pop(2)
print(my_list)
Th

This will output:


[1, 2, 4]

In this example, the pop() method is used to remove the element at index
position 2, which is the number 3. The pop() method also returns the value of the
removed element, so you can store it in a variable if you need to. If you don't pass
an index to the pop() method, it will remove and return the last element of the list.
30) What is a tuple in Python?
In Python, a tuple is an ordered, immutable collection of elements. This means
that once a tuple is created, you cannot change its contents.
Tuples are very similar to lists, but there are a few key differences:

● Tuples are immutable, whereas lists are mutable.


● Tuples are usually written with parentheses, whereas lists are usually
written with square brackets.
● Tuples can contain any type of object, just like lists.

y
Here's an example of a tuple in Python:

m
my_tuple = (1, 2, 3, 'four')

de
In this example, my_tuple contains four elements: the integers 1, 2, and 3, and the
string 'four'. Because tuples are immutable, you cannot add, remove, or modify

ca
elements once the tuple has been created.

You can access individual elements of a tuple using indexing, just like with lists:
gA
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: 'four'

Tuples can be useful when you need to group together related data that should
tin

not be changed after it is created, such as a point in 2D space or a date and time.

31) What is the difference between a list and a tuple in Python?


es

In Python, lists and tuples are both used to store ordered collections of elements,
but there are several key differences between them:
1. Mutability: Lists are mutable, meaning you can change their contents (add,
eT

remove or modify elements) after they are created, while tuples are
immutable, meaning you cannot change their contents once they are
created.
Th

2. Syntax: Lists are defined with square brackets [], while tuples are defined
with parentheses ().
3. Performance: Tuples are generally faster than lists for accessing elements
because they are stored in a contiguous block of memory, whereas lists
may be scattered in memory due to their ability to grow and shrink
dynamically.
4. Usage: Lists are commonly used for storing and manipulating collections
of data, especially when the size of the collection is not known in advance
and may change over time. Tuples are commonly used for grouping
together related pieces of data that should not be changed, such as a date
and time, or a point in 2D or 3D space.

Here are some examples to illustrate these differences:

# Define a list
my_list = [1, 2, 3]

# Add an element to the list

y
my_list.append(4)

m
# Modify an element in the list
my_list[1] = 5

de
# Define a tuple
my_tuple = (1, 2, 3)

ca
# Try to modify an element in the tuple (this will raise an error)
my_tuple[1] = 5
gA
# Access an element in the tuple
x = my_tuple[0]
tin

In this example, you can see that lists can be modified by adding or changing
elements, while tuples cannot. However, tuples are faster to access than lists
because they are stored in a contiguous block of memory.
es

32) What is a dictionary in Python?


In Python, a dictionary is a collection of key-value pairs, where each key maps to
eT

a value. Dictionaries are also sometimes called "associative arrays" or "hash


maps" in other programming languages.
Dictionaries are similar to lists and tuples in that they are used to store and
Th

organize data, but they are different in several important ways:


● Instead of using an index to access an element, you use a key to look up a
value in a dictionary.
● Keys in a dictionary must be unique, but values can be duplicated.
● Dictionaries are unordered, meaning the order in which the key-value pairs
are stored is not guaranteed.

Here's an example of a dictionary in Python:


my_dict = {'apple': 2, 'banana': 3, 'orange': 1}
In this example, the keys are 'apple', 'banana', and 'orange', and the corresponding
values are 2, 3, and 1. You can access the values in the dictionary using the keys,
like this:
print(my_dict['banana']) # Output: 3

You can also add, remove, or modify key-value pairs in a dictionary after it is
created, like this:
# Add a new key-value pair

y
my_dict['pear'] = 4

m
# Modify an existing value
my_dict['banana'] = 5

de
# Remove a key-value pair
del my_dict['orange']

ca
Dictionaries are very useful for representing complex data structures, such as
configuration settings, user profiles, or network graphs, where you need to look
gA
up values based on a unique identifier (the key).

33) How do you access elements in a dictionary in Python?


In Python, you can access elements in a dictionary using the keys as the index.
tin

Here's an example:
# Define a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}
es

# Access a value by key


print(my_dict['banana']) # Output: 3
eT

In this example, the key 'banana' is used to access the corresponding value 3 in
the dictionary my_dict.
Th

If you try to access a key that does not exist in the dictionary, you will get a
KeyError:
# This will raise a KeyError
print(my_dict['pear'])

To avoid a KeyError, you can use the get() method, which returns None if the key
is not found:
# Use the get() method to avoid a KeyError
print(my_dict.get('pear')) # Output: None
You can also provide a default value to the get() method, which will be returned if
the key is not found:
# Use a default value with the get() method
print(my_dict.get('pear', 0)) # Output: 0

In this example, the default value 0 is returned because the key 'pear' is not found
in the dictionary.

y
34) How do you add an element to a dictionary in Python?
In Python, you can add a new key-value pair to a dictionary by assigning a value

m
to a new or existing key. Here's an example:

de
# Define a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}

ca
# Add a new key-value pair
my_dict['pear'] = 4
gA
# Print the updated dictionary
print(my_dict)
# Output: {'apple': 2, 'banana': 3, 'orange': 1, 'pear': 4}
tin

In this example, the key 'pear' is added to the dictionary my_dict with the
corresponding value 4.
es

If the key already exists in the dictionary, assigning a new value to the key will
overwrite the existing value:
# Modify an existing key-value pair
eT

my_dict['banana'] = 5

# Print the updated dictionary


Th

print(my_dict)
# Output: {'apple': 2, 'banana': 5, 'orange': 1, 'pear': 4}

In this example, the value of the existing key 'banana' is changed from 3 to 5.

You can also use the update() method to add multiple key-value pairs to a
dictionary at once, using another dictionary or an iterable of key-value pairs:
# Add multiple key-value pairs with the update() method
my_dict.update({'kiwi': 6, 'grape': 7})
# Print the updated dictionary
print(my_dict)
# Output: {'apple': 2, 'banana': 5, 'orange': 1, 'pear': 4, 'kiwi': 6, 'grape': 7}

In this example, the update() method is used to add the key-value pairs 'kiwi': 6
and 'grape': 7' to the dictionary my_dict.

35) How do you remove an element from a dictionary in Python?

y
In Python, you can remove an element from a dictionary using the del keyword or
the pop() method.

m
To remove an element using del, you simply specify the key of the element you
want to remove:

de
# Define a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}

ca
# Remove an element using del
del my_dict['banana']
gA
# Print the updated dictionary
print(my_dict)
# Output: {'apple': 2, 'orange': 1}
tin

In this example, the key 'banana' and its corresponding value 3 are removed from
the dictionary my_dict.
es

You can also use the pop() method to remove an element from a dictionary and
return its value:
eT

# Define a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}
Th

# Remove an element using pop()


value = my_dict.pop('banana')

# Print the removed value and the updated dictionary


print(value) # Output: 3
print(my_dict) # Output: {'apple': 2, 'orange': 1}
In this example, the key 'banana' and its corresponding value 3 are removed from
the dictionary my_dict, and the value 3 is returned and stored in the variable
value.
If you try to remove a key that does not exist in the dictionary, you will get a
KeyError. To avoid a KeyError, you can use the pop() method with a default value,
which will be returned if the key is not found:
# Use pop() with a default value to avoid a KeyError
value = my_dict.pop('pear', 0)

# Print the removed value and the updated dictionary


print(value) # Output: 0

y
print(my_dict) # Output: {'apple': 2, 'orange': 1}

m
In this example, the key 'pear' is not found in the dictionary my_dict, so the default
value 0 is returned and stored in the variable value. The dictionary my_dict is not
modified.

de
36) What is a set in Python?
In Python, a set is an unordered collection of unique elements. This means that

ca
each element in a set can only appear once, and the elements are not stored in
any particular order.
You can create a set in Python by enclosing a comma-separated sequence of
gA
values inside curly braces {}, or by using the set() constructor. For example:
# Create a set with curly braces
my_set = {1, 2, 3, 4}
tin

# Create a set with the set() constructor


my_set = set([1, 2, 3, 4])
es

In both cases, the resulting set my_set contains the elements 1, 2, 3, and 4.
You can also create an empty set using the set() constructor, like this:
# Create an empty set
eT

my_set = set()

37) How do you create a set in Python?


Th

You can create a set in Python using either curly braces {} or the set()
constructor.
To create a set using curly braces, you simply enclose a comma-separated
sequence of values inside curly braces, like this:
my_set = {1, 2, 3, 4}
In this example, my_set is a set containing the elements 1, 2, 3, and 4.

Alternatively, you can create a set using the set() constructor. To do this, you
pass a sequence of values to the set() constructor as an argument, like this:
my_set = set([1, 2, 3, 4])
In this example, my_set is also a set containing the elements 1, 2, 3, and 4.
You can also create an empty set using the set() constructor:

my_set = set()
In this case, my_set is an empty set with no elements.

38) How do you add an element to a set in Python?


In Python, you can add an element to a set using the add() method. Here's an

y
example:

m
my_set = {1, 2, 3} # create a set with elements 1, 2, and 3
my_set.add(4) # add the element 4 to the set

de
print(my_set) # prints {1, 2, 3, 4}

In this example, the add() method is called on the set my_set with the argument

ca
4. This adds the element 4 to the set. The print() statement then displays the
updated set.

39) How do you remove an element from a set in Python?


gA
In Python, you can remove an element from a set using the remove() or discard()
method. Here's an example:
tin

my_set = {1, 2, 3, 4} # create a set with elements 1, 2, 3, and 4


my_set.remove(3) # remove the element 3 from the set
print(my_set) # prints {1, 2, 4}
es

In this example, the remove() method is called on the set my_set with the
argument 3. This removes the element 3 from the set. The print() statement then
eT

displays the updated set.

If you are not sure whether an element is in the set or not, you can use the
Th

discard() method instead. The discard() method works like the remove() method,
but if the element is not in the set, it does not raise an error. Here's an example:

my_set = {1, 2, 3, 4} # create a set with elements 1, 2, 3, and 4


my_set.discard(3) # remove the element 3 from the set
my_set.discard(5) # try to remove the element 5, which is not in the set
print(my_set) # prints {1, 2, 4}
In this example, the discard() method is called twice. The first call removes the
element 3 from the set, just like the remove() method. The second call tries to
remove the element 5, which is not in the set. Since the discard() method does
not raise an error in this case, the set remains unchanged. The print() statement
then displays the updated set.

40) What is a module in Python?


In Python, a module is a file containing Python definitions and statements. The
file name is the module name with the suffix .py appended.

y
A module can define functions, classes, and variables that can be used by other

m
Python programs or modules. Modules are useful for organizing code into
reusable and sharable units.

de
To use a module in a Python program, you can import it using the import
statement. For example, if you have a module named mymodule.py that defines a

ca
function myfunction(), you can import the module and use the function like this:
import mymodule
mymodule.myfunction()
gA
In this example, the import statement loads the mymodule module into the
program. The mymodule.myfunction() statement then calls the myfunction()
function defined in the module.
tin

You can also import specific functions or variables from a module using the from
keyword. For example:
es

from mymodule import myfunction


myfunction()
eT

In this example, the from keyword specifies that only the myfunction() function
should be imported from the mymodule module. The myfunction() statement
then calls the function directly without prefixing it with the module name.
Th

41) How do you import a module in Python?


In Python, you can import a module using the import statement. Here are some
examples of how to import modules:
To import a module by its name:
import module_name

To import a module with an alias:


import module_name as alias_name
To import a specific function or variable from a module:
from module_name import function_name, variable_name

To import all functions and variables from a module:


from module_name import *

Here's an example of how to import the built-in math module:

y
import math

m
print(math.sqrt(25)) # prints 5.0

In this example, the import statement loads the math module into the program.

de
The math.sqrt() statement then calls the sqrt() function defined in the module to
compute the square root of 25.
If you want to use a different name for the module, you can use an alias like this:

ca
import math as m
print(m.sqrt(25)) # prints 5.0
gA
In this example, the import statement loads the math module into the program
with the alias m. The m.sqrt() statement then calls the sqrt() function defined in
the module using the m alias.
tin

If you only need to use a specific function or variable from a module, you can use
the from keyword to import it directly like this:
from math import sqrt
es

print(sqrt(25)) # prints 5.0


In this example, the from keyword specifies that only the sqrt() function should
be imported from the math module. The sqrt() statement then calls the sqrt()
eT

function directly without prefixing it with the module name.

Note that importing all functions and variables from a module using the *
Th

wildcard can make the code less readable and more error-prone, so it is generally
not recommended. It is better to explicitly import only the functions and variables
that you need.

42) What is a package in Python?


In Python, a package is a way to organize related modules into a single
namespace or hierarchy. A package is simply a directory that contains Python
modules, and the directory must have a special file called __init__.py to be
recognized as a Python package.
Packages provide a way to organize code and make it easier to reuse and
maintain. By grouping related modules together, packages make it easier to
understand and navigate a codebase.

To use a module from a package, you can import it using the dot notation. For
example, suppose you have a package named mypackage and it contains a
module named mymodule. You can import the module in your code like this:
import mypackage.mymodule

y
Or, if you only need a specific function or class from the module, you can import it

m
directly:

from mypackage.mymodule import MyClass

de
Packages can be nested within other packages, creating a hierarchical
organization of code. For example, the popular data analysis library Pandas has a
package named pandas, which contains sub-packages like pandas.core,

ca
pandas.io, and pandas.plotting, each of which contain related modules.

43) How do you create a package in Python?


gA
To create a package in Python, follow these steps:
1. Create a directory with the name of your package. This will be the root
directory of your package.
2. Inside the package directory, create a file named __init__.py. This file is
tin

required to tell Python that this directory is a Python package.


3. Create one or more module files inside the package directory. These files
will contain the code for your package.
es

4. Optionally, you can create subdirectories inside the package directory to


further organize your code. Each subdirectory should also contain an
__init__.py file.
eT

Here is an example directory structure for a simple package named mypackage:

mypackage/
Th

__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
In this example, mypackage is the root directory of the package, and it contains
three files: __init__.py, module1.py, and module2.py. It also contains a
subdirectory named subpackage, which contains an __init__.py file and a module
file named module3.py.

Once you have created your package, you can import modules from it in the
same way as any other Python module:

import mypackage.module1
from mypackage import module2
from mypackage.subpackage import module3

y
m
Note that the path to the module includes the package name and any
subdirectories, separated by dots (.).

de
44) What is a virtual environment in Python?
In Python, a virtual environment is a tool that allows you to create a
self-contained environment that has its own installation directories, libraries, and

ca
configuration files. Essentially, it's a way to isolate your Python project and its
dependencies from your system-wide Python installation.
gA
By creating a virtual environment, you can install specific versions of Python and
packages without affecting other projects or the global Python installation on
your machine. This can be useful if you're working on multiple projects that
require different versions of Python or different versions of the same package.
tin

45) How do you create a virtual environment in Python?


To create a virtual environment in Python, you can use the built-in venv module.
es

Here are the steps to create a virtual environment in Python:

1. Open a terminal or command prompt.


eT

2. Navigate to the directory where you want to create your virtual


environment.
3. Run the following command to create a virtual environment. Replace
Th

env_name with the name you want to give to your virtual environment.

python -m venv env_name


If you have multiple versions of Python installed on your system, you can specify
the Python version you want to use. For example, if you have Python 3.9 installed
and want to create a virtual environment using Python 3.9, you can run:

python3.9 -m venv env_name


4. Once the virtual environment is created, you can activate it by running the
following command:
● On Windows:
env_name\Scripts\activate.bat

● On Unix or Linux:
source env_name/bin/activate

5. After activating the virtual environment, you can install packages or run Python

y
scripts as you normally would, and the virtual environment will use its own

m
isolated Python interpreter and package dependencies.

6. When you're finished working in the virtual environment, you can deactivate it

de
by running the following command:

deactivate

ca
That's it! You now know how to create and use virtual environments in Python.

46) What is pip in Python?


gA
pip is a package manager for Python that allows you to easily install, manage,
and remove Python packages and their dependencies. It is included by default
with most Python installations and is used by developers and users to install and
manage Python packages from the Python Package Index (PyPI) and other
tin

package repositories.

With pip, you can easily install packages by running a simple command in your
es

terminal or command prompt. For example, to install the requests package, you
can run:
pip install requests
eT

pip will automatically download the latest version of the requests package from
PyPI and install it on your system. You can also specify a specific version of a
Th

package to install or install a package from a local directory or URL.

pip also allows you to manage dependencies between packages by installing and
uninstalling packages and their dependencies in a way that ensures all
dependencies are satisfied and compatible with each other.

Some other common pip commands include:

● pip list: List all installed packages.


● pip freeze: List all installed packages and their versions in a format that
can be easily shared and used to reproduce an environment.
● pip install --upgrade package_name: Upgrade an installed package to the
latest version.
● pip uninstall package_name: Uninstall a package.

In summary, pip is a powerful and essential tool for working with Python
packages and their dependencies.

y
47) How do you install a package using pip in Python?
To install a package using pip in Python, you can follow these steps:

m
1. Open a terminal or command prompt.
2. Use the following command to install the package. Replace package_name

de
with the name of the package you want to install.
pip install package_name

ca
For example, to install the numpy package, you can run:
pip install numpy
gA
3. pip will automatically download the package from PyPI (Python Package
Index) and install it on your system. If the package has dependencies, pip will
also download and install the necessary dependencies.
tin

4. Once the package is installed, you can import it in your Python code and use it
as needed.
import package_name
es

That's it! You have successfully installed a package using pip in Python. You can
install as many packages as you need using the same process. Note that some
eT

packages may require additional setup or configuration before they can be used,
so be sure to read the package documentation for instructions on how to use it.

48) What is a traceback in Python?


Th

In Python, a traceback is a report that shows the sequence of function calls that
led to an error or exception. When a Python program encounters an error, it
generates a traceback to help you identify the cause of the error and the location
in your code where it occurred.
A traceback typically includes the following information:
● The type of exception that was raised (e.g., TypeError, NameError,
ValueError, etc.)
● The message associated with the exception, which provides more detailed
information about the error.
● The sequence of function calls that led to the error, starting with the line of
code that raised the exception and working backwards through the call
stack.
● The line number and file name for each function call in the call stack.
Here is an example of a traceback:

Traceback (most recent call last):

y
File "example.py", line 4, in <module>

m
c=a+b
TypeError: unsupported operand type(s) for +: 'int' and 'str'

de
In this example, the traceback shows that a TypeError exception was raised on
line 4 of the example.py file, where the program attempted to add an integer and
a string together. The traceback also shows that the error was caused by the line

ca
of code c = a + b, which is highlighted with an arrow (^) to indicate the specific
location of the error.
gA
Tracebacks can be very helpful for debugging and troubleshooting Python
programs, as they provide detailed information about where errors occurred and
what led to them. When you encounter an error in your Python code, the
traceback can help you identify the source of the problem and make the
tin

necessary corrections.

49) How do you debug a Python code?


es

Debugging is the process of identifying and fixing errors in your code. Here are
some steps you can follow to debug your Python code:
1. Identify the problem: The first step in debugging is to identify the problem.
eT

This may involve reading error messages, examining the output of your
code, or using print statements to trace the flow of your program.
2. Isolate the problem: Once you have identified the problem, try to isolate it
Th

to a specific section of your code. Comment out other parts of your code
to focus on the part that is causing the error.
3. Use print statements: One of the simplest ways to debug your code is to
use print statements to check the value of variables at different points in
your program. Print statements can help you identify where the problem is
occurring and what values are being used.
4. Use a debugger: Python comes with a built-in debugger that you can use to
step through your code, set breakpoints, and examine variables. To use the
debugger, you need to import the pdb module and add the pdb.set_trace()
function to your code where you want to start debugging.
5. Use an IDE: An integrated development environment (IDE) can also help
you debug your code by providing features like syntax highlighting, code
completion, and a built-in debugger. Some popular Python IDEs include
PyCharm, Visual Studio Code, and Spyder.
6. Read documentation and search for solutions online: If you are still having
trouble debugging your code, try reading the documentation for the
libraries or modules you are using, or search for solutions online. There

y
may be others who have encountered similar problems and posted

m
solutions or workarounds.

Remember, debugging is a process that requires patience and persistence. Keep

de
trying different approaches until you find a solution to your problem.

50) What is a syntax error in Python?

ca
In Python, a syntax error is an error that occurs when the code you have written
does not follow the syntax rules of the Python language. Python has a set of
rules or grammar for how the code should be written, and if these rules are not
gA
followed, the interpreter will raise a syntax error.
Some common examples of syntax errors in Python include:
● Forgetting to close a parenthesis, bracket, or quotation mark
● Misspelling a keyword or variable name
tin

● Using an invalid character in a variable name


● Missing a colon at the end of a for or if statement
● Using an incorrect number of arguments when calling a function
es

● Using an incorrect operator or operator order

Here's an example of a syntax error in Python:


eT

>>> print("Hello, world!'


File "<stdin>", line 1
print("Hello, world!'
Th

^
SyntaxError: EOL while scanning string literal
In this example, the syntax error occurred because the closing quotation mark
was missing from the string. The interpreter detected the error and raised a
SyntaxError with a message indicating that the error occurred on the line where
the string was defined.

Syntax errors can be frustrating for beginners, but they are an important part of
the Python language. By enforcing a set of rules for how code should be written,
Python helps ensure that your code is consistent, readable, and easier to debug.
When you encounter a syntax error, the interpreter will often provide a helpful
message indicating where the error occurred and what the problem might be.

51) What is a runtime error in Python?


In Python, a runtime error (also known as an exception) is an error that occurs
while a program is running. Unlike syntax errors, which occur during the
compilation or parsing of your code, runtime errors occur during the execution of
your code.

y
A runtime error can occur for many reasons, such as:

m
● Trying to divide a number by zero (ZeroDivisionError)
● Trying to access an item in a list or dictionary that does not exist

de
(IndexError or KeyError)
● Passing the wrong type of argument to a function (TypeError)
● Trying to open a file that does not exist (FileNotFoundError)

ca
● Running out of memory (MemoryError)
Here's an example of a runtime error in Python:
gA
>>> x = 5 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
tin

In this example, a ZeroDivisionError occurred because the program attempted to


divide a number by zero. The interpreter raised a traceback that showed where
es

the error occurred and what type of error it was.

When a runtime error occurs, Python will usually provide a traceback that shows
eT

the sequence of function calls that led to the error. This traceback can be helpful
in identifying the source of the error and fixing the problem.
Th

To handle runtime errors, you can use a try-except block in your code. This allows
you to catch specific types of exceptions and handle them in a way that makes
sense for your program. For example:

try:
x=5/0
except ZeroDivisionError:
print("Cannot divide by zero")
In this example, the program attempts to divide a number by zero, but the
ZeroDivisionError is caught by the except block, which prints a message
indicating that the division cannot be performed.

52) What is a logical error in Python?


In Python, a logical error is an error that occurs when a program runs without
raising any syntax or runtime errors, but produces incorrect or unexpected
results. Logical errors are also known as bugs, and they can be difficult to identify
and fix, especially in large programs.

y
Logical errors occur when the code does not match the intended logic or when

m
there is a flaw in the algorithm used to solve a problem. They can be caused by a
wide range of issues, such as incorrect use of variables, incorrect data types,

de
incorrect assumptions, and incorrect or incomplete understanding of the
problem.

ca
Here's an example of a logical error in Python:
def calculate_average(numbers):
total = 0
gA
for number in numbers:
total += number
average = total / len(numbers)
return average
tin

numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
es

print("The average is:", average)

In this example, the calculate_average function calculates the average of a list of


eT

numbers. However, there is a logical error in the function: the calculation of the
average is incorrect. Instead of dividing the total by the length of the list, the
function divides the length of the list by the total. As a result, the program
Th

produces an incorrect average:


The average is: 0.5

To fix logical errors, it is important to carefully examine the code and identify
where the error is occurring. Debugging techniques such as printing intermediate
values, using a debugger, and stepping through the code can be helpful in
identifying and fixing logical errors. It is also important to test the code
thoroughly to ensure that it produces the correct results under a range of input
conditions.
53) What is an assertion in Python?
In Python, an assertion is a statement that checks whether a condition is true,
and raises an exception if it is not. Assertions are used to validate assumptions
made by the program, and can be used to catch logical errors and ensure that the
program is working as intended.
Here's an example of an assertion in Python:

def calculate_average(numbers):
assert len(numbers) > 0, "The list of numbers cannot be empty"

y
total = sum(numbers)

m
average = total / len(numbers)
return average

de
numbers = [1, 2, 3, 4, 5]
average = calculate_average(numbers)
print("The average is:", average)

ca
In this example, the calculate_average function calculates the average of a list of
numbers. Before performing the calculation, the function includes an assertion
gA
statement that checks whether the list of numbers is empty. If the list is empty,
the assertion raises an AssertionError with the message "The list of numbers
cannot be empty".
tin

Assertions can be used in many different ways in Python, and can be especially
useful in debugging and testing code. By including assertions in your code, you
can catch errors early and ensure that your program is behaving as expected.
es

However, it's important to note that assertions should not be used as a


replacement for error handling and should be used judiciously, as they can slow
down the execution of your code.
eT

54) What is a docstring in Python?


In Python, a docstring is a string literal that is used to document a module, class,
Th

function, or method. Docstrings are typically placed at the beginning of the code
block, immediately following the definition of the module, class, function, or
method.
Docstrings are enclosed in triple quotes (either single or double), and can span
multiple lines. They provide a concise summary of the code's purpose and
functionality, as well as any parameters, return values, or side effects associated
with the code.
55) How do you write a docstring in Python?
In Python, a docstring is written as a string literal that immediately follows the
definition of a module, class, function, or method. The docstring is enclosed in
triple quotes (either single or double) and can span multiple lines. Here's an
example of a function with a docstring:

def calculate_average(numbers):
"""
Calculate the average of a list of numbers.

y
m
Args:
numbers (list): A list of numbers.

de
Returns:
float: The average of the numbers.

Raises:

""" ca
ValueError: If the list of numbers is empty.
gA
if not numbers:
raise ValueError("The list of numbers cannot be empty")
total = sum(numbers)
average = total / len(numbers)
tin

return average
In this example, the docstring provides a brief description of the
calculate_average function, including the purpose of the function, the arguments
es

it takes, the return value, and any potential exceptions that it can raise.
When writing a docstring, it's important to follow a few guidelines to ensure that
your docstring is clear, concise, and easy to read. Here are some tips for writing
eT

effective docstrings:
1. Use clear and descriptive language to describe the purpose and behavior
of the code.
Th

2. Include information about the function's arguments, return values, and


potential exceptions.
3. Use a consistent format for documenting function arguments, typically
starting with the argument name, followed by a description of the
argument and its type.
4. Use examples and sample code to illustrate how the function is used.
5. Use plain text formatting to make the docstring easy to read, such as
indentation, bulleted lists, and horizontal lines.
By following these guidelines, you can create clear and comprehensive
docstrings that make your code easier to understand and use.

56) What is a lambda function in Python?


In Python, a lambda function (also known as an anonymous function) is a small,
anonymous function that can be defined inline without being bound to a name.
Lambda functions are useful for writing simple, one-line functions that are not
needed elsewhere in the code.

y
A lambda function is defined using the lambda keyword, followed by a
comma-separated list of arguments (if any), a colon :, and an expression that

m
returns the value of the function. Here's a simple example:

de
# Define a lambda function that adds two numbers
add_numbers = lambda x, y: x + y
# Use the lambda function to add two numbers

ca
result = add_numbers(2, 3)
print(result) # Output: 5
gA
In this example, we define a lambda function called add_numbers that takes two
arguments (x and y) and returns their sum. We then use the lambda function to
add the numbers 2 and 3, and store the result in the result variable.
tin

Lambda functions are often used in conjunction with built-in functions like map(),
filter(), and reduce(), which take other functions as arguments. For example,
here's how you might use a lambda function with the filter() function to create a
es

new list of only the even numbers from an existing list:


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
eT

print(even_numbers) # Output: [2, 4, 6, 8, 10]

In this example, we use a lambda function to define the filter condition, which
Th

checks if a number is even by testing if its remainder after division by 2 is zero.


We then use the filter() function to apply the lambda function to the numbers list,
and create a new list (even_numbers) that only contains the even numbers from
the original list.
57) How do you use a lambda function in Python?
In Python, you can use a lambda function by defining it inline and passing it as an
argument to another function or assigning it to a variable.

Here's an example of how to use a lambda function with the built-in map()
function to apply the lambda function to each element of a list:

# Define a lambda function to square a number


square = lambda x: x**2

y
m
# Use the map() function with the lambda function to create a new list of squared
numbers
numbers = [1, 2, 3, 4, 5]

de
squared_numbers = list(map(square, numbers))

print(squared_numbers) # Output: [1, 4, 9, 16, 25]

ca
In this example, we define a lambda function called square that takes one
argument (x) and returns its square. We then use the map() function to apply the
gA
square lambda function to each element of the numbers list, and create a new
list (squared_numbers) that contains the squared values.

Lambda functions are often used in conjunction with other built-in functions like
tin

filter(), reduce(), and sorted(), which take other functions as arguments. For
example, here's how you might use a lambda function with the filter() function to
create a new list of only the even numbers from an existing list:
es

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
eT

print(even_numbers) # Output: [2, 4, 6, 8, 10]

In this example, we use a lambda function to define the filter condition, which
Th

checks if a number is even by testing if its remainder after division by 2 is zero.


We then use the filter() function to apply the lambda function to the numbers list,
and create a new list (even_numbers) that only contains the even numbers from
the original list.
58) What is a map function in Python?
In Python, map() is a built-in function that applies a given function to each
element of an iterable (such as a list, tuple, or set) and returns an iterator that
yields the results.
The map() function takes two arguments: a function and an iterable. The function
argument is the function that will be applied to each element of the iterable, and
the iterable argument is the sequence of elements to be processed. Here's a
simple example:

y
# Define a function to square a number

m
def square(x):
return x**2

de
# Use the map() function to square each element of a list
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)

ca
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
gA
In this example, we define a function called square that takes one argument (x)
and returns its square. We then use the map() function to apply the square
function to each element of the numbers list, and create a new iterator
(squared_numbers) that yields the squared values.
tin

map() can also be used with lambda functions to create simple, one-line
functions inline. For example:
es

# Use the map() function with a lambda function to create a new list of squared
numbers
numbers = [1, 2, 3, 4, 5]
eT

squared_numbers = map(lambda x: x**2, numbers)

print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]


Th

In this example, we define a lambda function that takes one argument (x) and
returns its square. We then use the map() function to apply the lambda function
to each element of the numbers list, and create a new iterator
(squared_numbers) that yields the squared values.
59) How do you use a map function in Python?
In Python, map() is a built-in function that applies a given function to each
element of an iterable (such as a list, tuple, or set) and returns an iterator that
yields the results.

The map() function takes two arguments: a function and an iterable. The function
argument is the function that will be applied to each element of the iterable, and
the iterable argument is the sequence of elements to be processed. Here's a
simple example:

y
m
# Define a function to square a number
def square(x):
return x**2

de
# Use the map() function to square each element of a list
numbers = [1, 2, 3, 4, 5]

ca
squared_numbers = map(square, numbers)

print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]


gA
In this example, we define a function called square that takes one argument (x)
and returns its square. We then use the map() function to apply the square
function to each element of the numbers list, and create a new iterator
tin

(squared_numbers) that yields the squared values.

map() can also be used with lambda functions to create simple, one-line
es

functions inline. For example:

# Use the map() function with a lambda function to create a new list of squared
eT

numbers
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)
Th

print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]

In this example, we define a lambda function that takes one argument (x) and
returns its square. We then use the map() function to apply the lambda function
to each element of the numbers list, and create a new iterator
(squared_numbers) that yields the squared values.
60) What is a filter function in Python?
In Python, the filter() function is a built-in function that allows you to filter out
elements from an iterable object (e.g., list, tuple, dictionary, set, etc.) based on a
specific condition.

The filter() function takes two arguments: a function and an iterable. The function
takes one argument, and the iterable is the object you want to filter. The function
should return a Boolean value (True or False) based on the condition you want to
filter the iterable.

y
Here is the syntax of the filter() function:

m
filter(function, iterable)
The function argument can be any function that takes one argument and returns
a Boolean value. The iterable argument can be any iterable object, such as a list,

de
tuple, set, or dictionary.

The filter() function returns a filter object, which is an iterator that yields the items

ca
from the iterable for which the function returns True. You can convert the filter
object into a list or tuple using the built-in list() or tuple() functions, respectively.
gA
Here is an example of using the filter() function to filter out even numbers from a
list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))
tin

print(filtered_numbers) # Output: [2, 4, 6, 8, 10]

In this example, the lambda function checks whether the number is even or not.
es

The filter() function applies the lambda function to each element of the list and
returns a new list with only the even numbers.
eT

61) How do you use a filter function in Python?


To use the filter function in Python, you need to follow these steps:
1. Define a function that takes one argument and returns a Boolean value
Th

based on a specific condition. This function will be used as the first


argument of the filter() function.
2. Create an iterable object, such as a list, tuple, set, or dictionary, that you
want to filter.
3. Call the filter() function with the function and iterable object as arguments.
4. Convert the filter object into a list or tuple using the built-in list() or tuple()
functions, respectively.
Here is an example of using the filter() function to filter out even numbers from a
list:
# Define a function to filter out even numbers
def is_even(n):
return n % 2 == 0

# Create a list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use the filter function to filter out even numbers

y
filtered_numbers = list(filter(is_even, numbers))

m
# Print the filtered numbers
print(filtered_numbers) # Output: [2, 4, 6, 8, 10]

de
In this example, the is_even() function takes a number as an argument and
returns True if the number is even, and False otherwise. The filter() function

ca
applies the is_even() function to each element of the numbers list and returns a
new list with only the even numbers. Finally, the list() function is used to convert
the filter object into a list.
gA
62) What is a reduce function in Python?
In Python, the reduce() function is a built-in function in the functools module that
allows you to apply a function to an iterable object (e.g., list, tuple, dictionary, set,
tin

etc.) in a cumulative way. It takes the first two elements of the iterable object and
applies the function to them, then takes the result and applies the function to it
and the next element of the iterable, and so on until all the elements have been
es

processed.

The reduce() function takes two arguments: a function and an iterable. The
eT

function takes two arguments and returns a single value. The iterable is the
object you want to apply the function to.
Th

Here is the syntax of the reduce() function:


reduce(function, iterable)

The function argument can be any function that takes two arguments and returns
a single value. The iterable argument can be any iterable object, such as a list,
tuple, set, or dictionary.
The reduce() function returns a single value, which is the result of applying the
function cumulatively to the elements of the iterable object.
Here is an example of using the reduce() function to calculate the sum of a list of
numbers:
from functools import reduce

numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers) # Output: 15

In this example, the lambda function takes two arguments, x and y, and returns

y
their sum. The reduce() function applies the lambda function cumulatively to the

m
elements of the numbers list and returns the sum of all the numbers.

63) How do you use a reduce function in Python?

de
To use the reduce() function in Python, you need to follow these steps:
1. Import the functools module using the import keyword.
2. Define a function that takes two arguments and returns a single value. This

ca
function will be used as the first argument of the reduce() function.
3. Create an iterable object, such as a list, tuple, set, or dictionary, that you
want to apply the function to.
gA
4. Call the reduce() function with the function and iterable object as
arguments.
5. Store the result of the reduce() function in a variable.
Here is an example of using the reduce() function to calculate the product of a
tin

list of numbers:

# Import the functools module


es

from functools import reduce

# Define a function to calculate the product of two numbers


eT

def multiply(x, y):


return x * y
Th

# Create a list of numbers


numbers = [1, 2, 3, 4, 5]

# Use the reduce function to calculate the product of the numbers


product_of_numbers = reduce(multiply, numbers)

# Print the product of the numbers


print(product_of_numbers) # Output: 120
In this example, the multiply() function takes two numbers as arguments and
returns their product. The reduce() function applies the multiply() function
cumulatively to the elements of the numbers list and returns the product of all the
numbers. Finally, the result of the reduce() function is stored in the
product_of_numbers variable.

64) What is a list comprehension in Python?


In Python, list comprehension is a concise and efficient way to create a new list
based on an existing list or other iterable object, such as a tuple, set, or

y
dictionary. It allows you to create a new list by applying an expression to each
element of an iterable, and optionally filtering the elements based on a condition.

m
The syntax of list comprehension is as follows:

de
new_list = [expression for item in iterable if condition]
where new_list is the name of the new list you want to create, expression is the
operation you want to perform on each element of the iterable, item is the current

ca
element of the iterable, and condition is an optional condition that filters the
elements of the iterable based on a Boolean expression.
gA
Here is an example of using list comprehension to create a new list that contains
the squares of the elements of an existing list:

numbers = [1, 2, 3, 4, 5]
tin

squares = [n**2 for n in numbers]


print(squares) # Output: [1, 4, 9, 16, 25]
es

In this example, the squares list is created using list comprehension. The
expression n**2 is applied to each element n of the numbers list to compute the
square of each element. The resulting squares are then added to the squares list.
eT

65) How do you use a list comprehension in Python?


To use list comprehension in Python, you need to follow these steps:
Th

1. Start with an iterable object, such as a list, tuple, set, or dictionary, that you
want to apply the list comprehension to.
2. Write an expression that specifies the operation you want to perform on
each element of the iterable.
3. Use a for loop to iterate over the elements of the iterable.
4. Optionally, add a conditional statement to filter the elements of the iterable
based on a Boolean expression.
5. Enclose the expression and for loop in square brackets ([]) to create a new
list.
Here is an example of using list comprehension to create a new list that contains
only the even numbers from an existing list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
In this example, the even_numbers list is created using list comprehension. The
expression n adds each element of the numbers list to the even_numbers list.
The if statement filters out any element that is not even by checking if the

y
remainder of the division of the element by 2 is zero. The resulting even numbers
are then added to the even_numbers list.

m
66) What is a generator in Python?

de
In Python, a generator is a special type of iterator that allows you to iterate over a
sequence of values without creating the entire sequence in memory at once.
Generators are created using a special function called a generator function,
which uses the yield keyword instead of return to produce a series of values one
at a time.

ca
67) How do you use a generator in Python?
gA
To use a generator in Python, you need to follow these steps:
1. Define a generator function using the def keyword.
2. In the generator function, use the yield keyword to produce a sequence of
tin

values.
3. Call the generator function to create a generator object.
4. Use the generator object to iterate over the sequence of values produced
by the generator function.
es

5. Optionally, use a loop to iterate over a subset of the values produced by the
generator function.
eT

Here is an example of using a generator to generate a sequence of random


numbers between 0 and 1:
import random
Th

def random_numbers(n):
for i in range(n):
yield random.random()

gen = random_numbers(5)
for num in gen:
print(num)
In this example, the random_numbers() generator function uses a for loop to
produce a sequence of n random numbers using the random.random() function.
Each time the yield keyword is encountered, the current value of the
random.random() function is returned to the caller.

The random_numbers() function is then called with an argument of 5 to create a


generator object gen. The for loop is used to iterate over the sequence of random
numbers produced by the generator, printing each number to the console.

y
Note that in this example, we only iterate over the first 5 values produced by the

m
generator, even though the generator could theoretically produce an infinite
sequence of random numbers. This is because generators produce values lazily,
only generating the next value in the sequence when requested by the caller.

de
68) What is an iterator in Python?
In Python, an iterator is an object that can be used to traverse through a

ca
sequence of values, one at a time. An iterator must implement two methods:
__iter__() and __next__(). The __iter__() method returns the iterator object itself,
and the __next__() method returns the next value in the sequence.
gA
When an iterator is created, it begins with the first value in the sequence. The
__next__() method is then called to retrieve each subsequent value in the
sequence, until there are no more values left. If the __next__() method is called
tin

when there are no more values in the sequence, it should raise the StopIteration
exception.
es

Iterators are used to iterate over sequences of data, such as lists, tuples, and
dictionaries. However, iterators can also be used to iterate over custom data
structures, such as trees or graphs, as long as they implement the required
eT

iterator methods.
Here is an example of using an iterator to iterate over a list of names:
Th

names = ["Alice", "Bob", "Charlie", "David"]

it = iter(names)
print(next(it)) # prints "Alice"
print(next(it)) # prints "Bob"
print(next(it)) # prints "Charlie"
print(next(it)) # prints "David"
In this example, the iter() function is called to create an iterator object it from the
list of names. The next() function is then used to iterate over the sequence of
names produced by the iterator, printing each name to the console.

Note that if we try to call next() after the last name has been printed, a
StopIteration exception will be raised, indicating that there are no more values in
the sequence.

69) How do you use an iterator in Python?

y
In Python, an iterator is an object that allows you to traverse a sequence of
elements one by one. You can use an iterator in Python by following these steps:

m
1. Create an iterable object: An iterable object is any object that can be looped

de
over, such as a list, tuple, or string. For example, you can create a list of numbers
as follows:
numbers = [1, 2, 3, 4, 5]

ca
2. Create an iterator object: You can create an iterator object using the iter()
function. The iterator object will allow you to traverse the elements of the iterable
gA
object one by one. For example, you can create an iterator object for the numbers
list as follows:
numbers_iterator = iter(numbers)
tin

3.Traverse the iterable object using the iterator object: You can use a loop or a
comprehension to traverse the iterable object using the iterator object. For
example, you can use a loop to print the elements of the numbers list as follows:
es

for num in numbers_iterator:


print(num)
eT

This will output:


1
2
Th

3
4
5

4. Accessing elements using next(): You can use the next() function to access
the next element in the iterator. For example, you can use the next() function to
print the first element of the numbers list as follows:
print(next(numbers_iterator))
This will output:
1

If you try to call next() on an iterator that has already reached the end of the
sequence, it will raise a StopIteration exception.
Note that not all objects in Python are iterable, and you may encounter errors if
you try to create an iterator object for an object that is not iterable.

70) What is a decorator in Python

y
In Python, a decorator is a special construct that can modify or enhance the
behavior of a function, method, or class without changing its source code. A

m
decorator is implemented as a function that takes another function as its
argument, modifies it in some way, and then returns the modified function.

de
71) What is namespace in Python?
A namespace is a naming system used to make sure that names are unique to
avoid naming conflicts.

ca
72) Is python case sensitive?
gA
Yes. Python is a case sensitive language.

73) what is indentation in python?


tin

Indentation refers to the spaces at the beginning of a code line. Where in other
programming languages the indentation in code is for readability only, the
indentation in Python is very important. Python uses indentation to indicate a
block of code.
es

74) Is indentation required in python?


eT

Indentation is necessary for Python. It specifies a block of code. All code within
loops, classes, functions, etc is specified within an indented block. It is usually
done using four space characters. If your code is not indented necessarily, it will
not execute accurately and will throw errors as well.
Th

75) What is the difference between Arrays and lists in Python?


Arrays and lists, in Python, have the same way of storing data. But, arrays can
hold only a single data type elements whereas lists can hold any data type
elements.
Example:
import array as arr
My_Array=arr.array('i',[4,5,6,7])
My_list=[1,'abc',1.20]
print(My_Array)
print(My_list)

Output:

y
array(‘i’, [4, 5, 6, 7]) [1, ‘abc’, 1.2]

m
76) What is __init__?
__init__ is a method or constructor in Python. This method is automatically called

de
to allocate memory when a new object/ instance of a class is created. All classes
have the __init__ method.
Here is an example of how to use it.

ca
class Employee:
def __init__(self, name, age,salary):
self.name = name
gA
self.age = age
self.salary = 20000
E1 = Employee("XYZ", 23, 20000)
tin

# E1 is the instance of class Employee.


#__init__ allocates memory for E1.
print(E1.name)
es

print(E1.age)
print(E1.salary)
eT

Output:

XYZ
23
Th

20000

77) What is self in Python?


Self is an instance or an object of a class. In Python, this is explicitly included as
the first parameter. However, this is not the case in Java where it’s optional. It
helps to differentiate between the methods and attributes of a class with local
variables.
The self variable in the init method refers to the newly created object while in
other methods, it refers to the object whose method was called.
78) What is the difference between range & xrange?
For the most part, xrange and range are the exact same in terms of functionality.
They both provide a way to generate a list of integers for you to use, however you
please. The only difference is that range returns a Python list object and x range
returns an xrange object.

This means that xrange doesn’t actually generate a static list at run-time like
range does. It creates the values as you need them with a special technique

y
called yielding. This technique is used with a type of object known as generators.

m
That means that if you have a really gigantic range you’d like to generate a list for,
say one billion, xrange is the function to use.

de
79) What is pickling and unpickling?
“Pickling” is the process whereby a Python object hierarchy is converted into a
byte stream, and “unpickling” is the inverse operation, whereby a byte stream

ca
(from a binary file or bytes-like object) is converted back into an object hierarchy.

80) How will you capitalize the first letter of string?


gA
In Python, the capitalize() method capitalizes the first letter of a string. If the
string already consists of a capital letter at the beginning, then, it returns the
original string.
tin

81) What is the usage of help() and dir() function in Python?


Help() and dir() both functions are accessible from the Python interpreter and
es

used for viewing a consolidated dump of built-in functions.

Help() function: The help() function is used to display the documentation string
eT

and also facilitates you to see the help related to modules, keywords, attributes,
etc.
Th

Dir() function: The dir() function is used to display the defined symbols.

82) How can the ternary operators be used in python?


The Ternary operator is the operator that is used to show the conditional
statements. This consists of the true or false values with a statement that has to
be evaluated for it.
Syntax:
The Ternary operator will be given as:
[on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y
The expression gets evaluated like if x<y else y, in this case if x<y is true then the
value is returned as big=x and if it is incorrect then big=y will be sent as a result.

83) What are negative indexes and why are they used?
The sequences in Python are indexed and it consists of the positive as well as
negative numbers. The numbers that are positive uses ‘0’ that is uses as first
index and ‘1’ as the second index and the process goes on like that.

y
The index for the negative number starts from ‘-1’ that represents the last index in

m
the sequence and ‘-2’ as the penultimate index and the sequence carries forward
like the positive number.

de
The negative index is used to remove any new-line spaces from the string and
allow the string to except the last character that is given as S[:-1]. The negative

ca
index is also used to show the index to represent the string in correct order.

84) Does Python have OOps concepts?


Python is an object-oriented programming language. This means that any
gA
program can be solved in python by creating an object model. However, Python
can be treated as a procedural as well as structural language
tin

85) 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
es

python.

86) What is the purpose of is, not and in operators?


eT

Operators are referred to as special functions that take one or more


values(operands) and produce a corresponding result.
is: returns the true value when both the operands are true (Example: “x” is
‘x’)
Th

not: returns the inverse of the boolean value based upon the operands
(example:”1” returns “0” and vice-versa.
In: helps to check if the element is present in a given Sequence or not.

87) How will you reverse a list in Python?


The function list.reverse() reverses the objects of a list.
88) 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())

89) How is Multithreading achieved in Python?


Python has a multi-threading package ,but commonly not considered as good
practice to use it as it will result in increased code execution time.

y
m
Python has a constructor called the Global Interpreter Lock (GIL). The GIL
ensures that only one of your ‘threads’ can execute at one time.The process
makes sure that a thread acquires the GIL, does a little work, then passes the GIL

de
onto the next thread.

This happens at a very Quick instance of time and that’s why to the human

ca
eye it seems like your threads are executing parallely, but in reality they are
executing one by one by just taking turns using the same CPU core.

90) What is slicing in Python?


gA
Slicing is a process used to select a range of elements from sequence data type
like list, string and tuple. Slicing is beneficial and easy to extract out the
elements. It requires a : (colon) which separates the start index and end index of
tin

the field. All the data sequence types List or tuple allows us to use slicing to get
the needed elements. Although we can get elements by specifying an index, we
get only a single element whereas using slicing we can get a group or appropriate
es

range of needed elements.


Syntax:
List_name[start:stop]
eT

91) Define Inheritance in Python?


When an object of child class has the ability to acquire the properties of a parent
Th

class then it is called inheritance. It is mainly used to acquire runtime


polymorphism and also it provides code reusability.

92) How can we create a constructor in Python programming?


The _init_ method in Python stimulates the constructor of the class. Creating a
constructor in Python can be explained clearly in the below example.
class Student:
def __init__(self,name,id):
self.id = id;
self.name = name;
def display (self):
print("ID: %d nName: %s"%(self.id,self.name))
stu1 =Student("nirvi",105)
stu2 = Student("tanvi",106)
#accessing display() method to print employee 1 information
stu1.display();
#accessing display() method to print employee 2 information
stu2.display();

y
Output:

m
ID: 1
Name: nirvi

de
ID: 106
Name: Tanvi

93) Does Python make use of access specifiers

ca
Python does not make use of access specifiers and also it does not provide a way to
access an instance variable. Python introduced a concept of prefixing the name of the
method, function, or variable by using a double or single underscore to act like the behavior
gA
of private and protected access specifiers.

94) What is polymorphism in Python?


By using polymorphism in Python we will understand how to perform a single
tin

task in different ways. For example, designing a shape is the task and various
possible ways in shapes are a triangle, rectangle, circle, and so on.

95) Define encapsulation in Python?


es

Encapsulation is one of the most important aspects of object-oriented


programming. The binding or wrapping of code and data together into a single
cell is called encapsulation. Encapsulation in Python is mainly used to restrict
eT

access to methods and variables.

96) What is data abstraction in Python?


Th

In simple words, abstraction can be defined as hiding unnecessary data and


showing or executing necessary data. In technical terms, abstraction can be
defined as hiding internal processes and showing only the functionality. In Python
abstraction can be achieved using encapsulation.

97) Does multiple inheritances are supported in Python?


Multiple inheritances are supported in python. It is a process that provides
flexibility to inherit multiple base classes in a child class.
An example of multiple inheritances in Python is as follows:
class Calculus:
def Sum(self,a,b):
return a+b;
class Calculus1:
def Mul(self,a,b):
return a*b;
class Derived(Calculus,Calculus1):
def Div(self,a,b):
return a/b;

y
d = Derived()

m
print(d.Sum(10,30))
print(d.Mul(10,30))
print(d.Div(10,30))

de
Output:
40
300
0.3333
ca
98) What is the syntax for creating an instance of a class in
gA
Python?
The syntax for creating an instance of a class is as follows:
<object-name> = <class-name>(<arguments>)
tin

99) What are the OOP's concepts available in Python?


Python is also an object-oriented programming language like other programming
es

languages. It also contains different OOP's concepts, and they are


Object
Class
eT

Method
Encapsulation
Abstraction
Inheritance
Th

Polymorphism
100) Write a program in Python to produce a Star triangle?
The code to produce a star triangle is as follows:
def pyfun(r):
for a in range(r):
print(' '*(r-x-1)+'*'*(2*x+1))
pyfun(9)

Output:

y
*
***

m
*****
*******

de
*********
***********
*************

ca
***************
*****************

101) Write a program to check whether the given number is prime


gA
or not?
The code to check prime number is as follows:
# program to check the number is prime or not
tin

n1 = 409
# num1 = int(input("Enter any one number: "))
# prime number is greater than 1
es

if n1 > 1:
# check the following factors
for x is in range of(2,num1):
eT

if (n1 % x) == 0:
print(n1,"is not a prime number")
print(x,"times",n1//x,"is",num)
Th

break
else:
print(n1,"is a prime number")
# if input number is smaller than
# or equal to the value 1, then it is not prime number
else:
print(n1,"is not a prime number")
Output:
409 is a prime number
102) Write Python code to check the given sequence is a
palindrome or not?
# Python code to check a given sequence
# is palindrome or not
my_string1 = 'MOM'
My_string1 = my_string1.casefold()
# reverse the given string
rev_string1 = reversed(my_string1)
# check whether the string is equal to the reverse of it or not

y
if list(my_string1) == list(rev_string1):

m
print("It is a palindrome")
else:

de
print("It is not a palindrome")
Output:
it is a palindrome

ca
103) Write Python code to sort a numerical dataset?
gA
The code to sort a numerical dataset is as follows:
list = [ "13", "16", "1", "5" , "8"]
list = [int(x) for x in the list]
list.sort()
tin

print(list)
Output:
es

1, 5, 8, 13, 16

104) Write a program to display the Fibonacci sequence in


eT

Python?
# Displaying Fibonacci sequence
n = 10
# first two terms
Th

n0 = 0
n1 = 1
#Count
x=0
# check if the number of terms is valid
if n <= 0:
print("Enter positive integer")
elif n == 1:
print("Numbers in Fibonacci sequence upto",n,":")
print(n0)
else:
print("Numbers in Fibonacci sequence upto",n,":")
while x < n:
print(n0,end=', ')
nth = n0 + n1
n0 = n1
n1 = nth

y
x += 1

m
Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

de
105) Write a program to count the number of capital letters in a
file?

ca
with open(SOME_LARGE_FILE) as countletter:
count = 0
text = countletter.read()
for character in text:
gA
if character.isupper():
count += 1
tin

106) How do you copy an object in Python?


To copy objects in Python we can use methods called copy.copy() or
copy.deepcopy().
es

107) Why do we use the split method in Python?


split() method in Python is mainly used to separate a given string.
eT

Example:
x = "Mindmajix Online Training"
print(a.split())
Th

Output:
[‘Mindmajix’, ‘Online’, ‘Training’]

You might also like