Python Interview QnA
Python Interview QnA
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
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
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
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:
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
print("Hello, world!")
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
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.
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.
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!"
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
x = 3.14
y = int(x)
print(y) # Output: 3
eT
y = str(x)
print(y) # Output: "42"
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
# 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 ("...").
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
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"
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
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
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.
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
keyboard as a string. The function takes a single argument, which is a string that
prompts the user for input. Here's an example:
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
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.
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
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
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
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
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
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
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.
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
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
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.
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
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.
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:
return sum
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
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.
ca
greet() # Output: Hello, Guest!
Note that default arguments must come after non-default arguments in the
function signature. For example, this is a valid function definition:
tin
Here, a and b are required parameters, while c and d are optional parameters with
default values of 0 and 1, respectively.
eT
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:
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.
def my_func():
global x
eT
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.
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
Lists are commonly used in Python for storing and manipulating collections of
data, such as sequences of numbers or strings.
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.
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
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)
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)
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
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:
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.
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.
# Define a list
my_list = [1, 2, 3]
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
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).
Here's an example:
# Define a dictionary
my_dict = {'apple': 2, 'banana': 3, 'orange': 1}
es
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(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.
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
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
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()
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.
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.
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
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:
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
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
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
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.
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:
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.
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
env_name with the name you want to give to your virtual environment.
● 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.
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
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.
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.
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:
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.
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.
de
trying different approaches until you find a solution to your problem.
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
^
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.
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
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.
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
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
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
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
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
In this example, we use a lambda function to define the filter condition, which
Th
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:
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))
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
In this example, we use a lambda function to define the filter condition, which
Th
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
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)
map() can also be used with lambda functions to create simple, one-line
es
# 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
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
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
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
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.
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:
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
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
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
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.
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
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.
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
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.
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.
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
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
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
print(E1.age)
print(E1.salary)
eT
Output:
XYZ
23
Th
20000
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.
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.
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.
python.
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.
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.
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
y
Output:
m
ID: 1
Name: nirvi
de
ID: 106
Name: Tanvi
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.
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.
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
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
***************
*****************
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
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
Example:
x = "Mindmajix Online Training"
print(a.split())
Th
Output:
[‘Mindmajix’, ‘Online’, ‘Training’]