This article is participating in Python Theme Month. See the link to the event for more details

100 Basic Python Interview Questions Part 1 (1-20) | Python topic month

100 Basic Python Interview Questions Part 2 (21-40) | Python topic month

100 Basic Python Interview Questions Part 3 (41-60) | Python topic month

100 Basic Python Interview Questions Part 4 (61-80) | Python topic month

100 Basic Python Interview Questions Part 5 (81-100) | Python topic month


100 Basic Python Interview Questions Part 5 (81-100) | Python topic month

Q-1: What is Python, what are the benefits of using it, and what do you understand about PEP 8? Q-2: What is the output of the following Python snippet? Prove your answer. Q-3: What statements can be used in Python if the program does not need an action but syntactically requires it? Q-4: What is the process of using “~” to get the home directory in Python? Q-5: What are the built-in types available in Python? Q-6: How do I find errors or perform static analysis in a Python application? Q-7: When to use Python decorators? Q-8: What are the main differences between lists and tuples? Q-9: How does Python handle memory management? Q-10: What are the main differences between lambda and DEF? Q-11: Write a reg expression using the Python reg expression module “re” to verify the email ID? Q-12: What do you think the output of the following code snippet is? Are there any errors in the code? Q-13: Are there switch or case statements in Python? If not, what is the same reason? Q-14: What is Python’s built-in function for iterating over sequences of numbers? Q-15: What are the possible optional statements in Python’s try-except block? Q-16: What is a string in Python? Q-17: What is a slice in Python? Q-18: What is %s in Python? Q-19: Are strings immutable or mutable in Python? Q-20: What are indexes in Python? Q-21: What is a docstring in Python? Q-22: What are functions in Python programming? Q-23: How many basic types of functions are there in Python? Q-24: How do we write functions in Python? Q-25: What are function calls or callable objects in Python? Q-26: What does the return keyword in Python do? Q-27: What is “call by value” in Python? Q-28: What is “call by reference” in Python? Q-29: What is the return value of trunc()? Q-30: Must Python functions return a value? Q-31: What does a continue do in Python? Q-32: What is the purpose of the id() function in Python? Q-33: * What is the role of args in Python? Q-34: What does **kwargs do in Python? Q-35: Does Python have a Main() method? Q-36: what does __ Name __ do in Python? Q-37: What is the purpose of “end” in Python? Q-38: When should you use “break” in Python? Q-39: What’s the difference between pass and continue in Python? What does the q-40: len() function do in Python? Q-41: What does the CHR () function do in Python? Q-42: What does the ord() function do in Python? Q-43: What is Rstrip() in Python? Q-44: What is a space in Python? Q-45: What is isalpha() in Python? Q-46: How do you use the split() function in Python? Q-47: What does the Join method in Python do? Q-48: What does the Title() method do in Python? Q-49: What makes CPython different from Python? Q-50: Which package is the fastest form of Python? Q-51: What is the GIL in Python? Q-52: How can Python be thread safe? Q-53: How does Python manage memory? Q-54: What is a tuple in Python? Q-55: What are dictionaries in Python programming? Q-56: What is a set in Python? Q-57: What is the use of dictionaries in Python? Q-58: Are Python lists linked? Q-59: What is a Class in Python? Q-60: What are attributes and methods in Python classes? Q-61: How do I assign a Class attribute at run time? Q-62: What is inheritance in Python programming? Q-63: What is a combination in Python? Q-64: What are errors and exceptions in Python programs? Q-65: How do you use Try/Except/Finally to handle exceptions in Python? Q-66: How do you throw exceptions for predefined conditions in Python? Q-67: What is a Python iterator? Q-68: What’s the difference between an Iterator and an Iterable? Q-69: What is a Python generator? Q-70: What are closures in Python? Q-71: What are decorators in Python? Q-72: How do you create a dictionary in Python? Q-73: How do you read a dictionary in Python? Q-74: How do I iterate over dictionary objects in Python? Q-75: How do you add elements to a dictionary in Python? Q-76: How do I remove elements of a dictionary in Python? Q-77: How do you check for the presence of keys in a dictionary? Q-78: What is the syntax for a list derivation in Python? Q-79: What is the syntax for dictionary understanding in Python? Q-80: What is the syntax for generator expressions in Python? Q-81: How do you write conditional expressions in Python? Q-82: How much do you know about Python enumerations? Q-83: What is the use of globals() in Python? Q-84: Why use the zip() method in Python? Q-85: What are classes or static variables in Python programming? Q-86: How does the ternary operator work in Python? Q-87: What does the “self” keyword do? Q-88: What are the different ways to copy objects in Python? Q-89: What is the purpose of docstrings in Python? Q-90: Which Python function will you use to convert numbers to strings? Q-91: How do you debug programs in Python? Is it possible to step Python code? Q-92: List some PDB commands for debugging Python programs? Q-93: What is the command for debugging a Python program? Q-94: How do you monitor program code flow in Python? Q-95: Why and when to use generators in Python? Q-96: What does the yield keyword do in Python? Q-97: How do I convert a list to another data type? Q-98: How do you count the number of occurrences of each item in the list without explicitly mentioning it? Q-99: What is NumPy and how is it better than lists in Python? Q-100: What are the different ways to create an empty NumPy array in Python?


Q-81: How do you write conditional expressions in Python?

We can use the following single statement as a conditional expression. Default if the condition is another statement

>>> no_of_days = 366
>>> is_leap_year = "Yes" if no_of_days == 366 else "No"
>>> print(is_leap_year)
Yes
Copy the code

Return to the directory


Q-82: How much do you know about Python enumerations?

When using iterators, sometimes we might have a use case to store the number of iterations. Python makes this easy by providing a built-in method called enumerate().

The enumerate() function appends the counter variable to the iterable and returns it as an “enumerate” object.

We can use this object directly in the “for” loop, or we can convert it to a list of tuples by calling the list() method. It has the following signature:

enumerate(iterable, to_begin=0)
Copy the code
Arguments:
iterable: array type object which enables iteration
to_begin: the base index for the counter is to get started, its default value is 0
Copy the code
# Example - enumerate function
alist = ["apple"."mango"."orange"] 
astr = "banana"
  
# Let's set the enumerate objects 
list_obj = enumerate(alist) 
str_obj = enumerate(astr) 
  
print("list_obj type:".type(list_obj))
print("str_obj type:".type(str_obj))

print(list(enumerate(alist)) )  
# Move the starting index to two from zero
print(list(enumerate(astr, 2)))
Copy the code

The output is:

list_obj type: <class 'enumerate'>
str_obj type: <class 'enumerate'>
[(0.'apple'), (1.'mango'), (2.'orange')]
[(2.'b'), (3.'a'), (4.'n'), (5.'a'), (6.'n'), (7.'a')]
Copy the code

Return to the directory


Q-83: What is the use of globals() in Python?

The globals() function in Python returns the current global symbol table as a dictionary object.

Python maintains a symbol table to hold all the necessary information about a program. This information includes the names of variables, methods, and classes used by the program.

All the information in this table is kept within the global scope of the program, and Python allows us to retrieve it using the globals() method.

Signature: globals()

Arguments: None
Copy the code
# Example: globals() function
x = 9
def fn() : 
    y = 3
    z = y + x
    Call the globals() method
    z = globals(to)'x'] = z
    return z
       
# Test code
ret = fn() 
print(ret)
Copy the code

The output is:

12
Copy the code

Return to the directory


Q-84: Why use the zip() method in Python?

The zip method allows us to map the corresponding indexes of multiple containers so that we can use them as a single unit.

Signature: 
 zip(*iterators)
Arguments: 
 Python iterables or collections (e.g., list, string, etc.)
Returns: 
 A single iterator object with combined mapped values
Copy the code
# Example: zip() method
  
emp = [ "tom"."john"."jerry"."jake" ] 
age = [ 32.28.33.44 ] 
dept = [ 'HR'.'Accounts'.'R&D'.'IT' ] 
  
Call zip() to map the values
out = zip(emp, age, dept)
  
Convert all values to print them by setting
out = set(out) 
  
# Display the final value
print ("The output of zip() is : ",end="") 
print (out)
Copy the code

The output is:

The output of zip(a)is : {('jerry'.33.'R&D'), ('jake'.44.'IT'), ('john'.28.'Accounts'), ('tom'.32.'HR')}
Copy the code

Return to the directory


Q-85: What are classes or static variables in Python programming?

In Python, all objects share public classes or static variables.

But for different objects, instances or non-static variables are completely different.

Programming languages such as C++ and Java require variables to be class variables using the static keyword. However, Python has a unique way of declaring static variables.

All names initialized with values in a class declaration become class variables. Those that get assignments in class methods are called instance variables.

# for
class Test: 
    aclass = 'programming' # A class variable 
    def __init__(self, ainst) : 
        self.ainst = ainst # An instance variable 
  
Object of class # CSStudent
test1 = Test(1) 
test2 = Test(2) 
  
print(test1.aclass)
print(test2.aclass)
print(test1.ainst)
print(test2.ainst)

Class variables can also be accessed using the class name
print(Test.aclass)
Copy the code

The output is:

programming
programming
1
2
programming
Copy the code

Return to the directory


Q-86: How does the ternary operator work in Python?

Ternary operators are alternatives to conditional statements. It combines true or false values with statements that you want to test.

The syntax is similar to the syntax given below.

[onTrue] if [condition] else [onFalse]

x, y = 35.75
smaller = x if x < y else y
print(smaller)
Copy the code

Return to the directory


Q-87: What does the “self” keyword do?

“Self” is a Python keyword that represents a variable that holds an instance of an object.

In almost all object-oriented languages, it is passed as a hidden parameter to a method.

Return to the directory


Q-88: What are the different ways to copy objects in Python?

There are two ways to copy objects in Python.

Copy. The copy () function

  • It copies files from the source to the target.
  • It returns a shallow copy of the parameter.

Copy. Deepcopy () function

  • It also generates copies of objects from source to target.
  • It returns a deep copy of the arguments you can pass to the function.

Return to the directory


Q-89: What is the purpose of docstrings in Python?

In Python, a docstring is what we call a docstring. It sets up the procedure for recording Python functions, modules, and classes.

Return to the directory


Q-90: Which Python function will you use to convert numbers to strings?

To convert a number to a string, use the built-in function STR (). If you need octal or hexadecimal representation, use the built-in functions OCT () or HEX ().

Please also check 💡.

Return to the directory


Q-91: How do you debug programs in Python? Is it possible to step Python code?

Yes, we can use the Python debugger (PDB) to debug any Python program. If we use the PDB to start a program, it can even let us step through the code.

Return to the directory


Q-92: List some PDB commands for debugging Python programs?

Here are some PDB commands to start debugging Python code.

  • Add a breakpoint (b)
  • Restore execution (c)
  • Step by step Debugging (s)
  • Let’s move to the next line (n).
  • Listing source code (L)
  • Print expression (p)

Return to the directory


Q-93: What is the command for debugging a Python program?

The following commands are useful for running Python programs in debug mode.

$ python -m pdb python-script.py
Copy the code

Return to the directory


Q-94: How do you monitor program code flow in Python?

In Python, we can use the settrace() method of the sys module to settrace hooks and monitor functions inside the program.

You need to define a trace callback method and pass it to the setTrace () function. The callback should specify three parameters, as shown below.

import sys

def trace_calls(frame, event, arg) :
    The # 'call' event occurs before the function is executed.
    ifevent ! ='call':
        return
    Next, check the frame data and print information.
    print 'Function name=%s, line num=%s' % (frame.f_code.co_name, frame.f_lineno)
    return

def demo2() :
    print 'in demo2()'

def demo1() :
    print 'in demo1()'
    demo2()

sys.settrace(trace_calls)
demo1()
Copy the code

Return to the directory


Q-95: Why and when to use generators in Python?

A generator in Python is a function that returns an iterable. We can iterate over the generator object using the yield keyword. But we can only do this once, because their values don’t persist in memory, they get them instantly.

Generators enable us to keep the execution of a function or step as long as we want to keep it. However, there are a few examples where using generators can be beneficial.

  • We can replace loops with generators to efficiently compute results involving large data sets.
  • Generators are useful when we don’t want all the results and want to postpone them for a while.
  • Instead of using callbacks, we can use generators instead of callbacks. We can write a loop inside the function that does the same thing as the callback and turn it into a generator.

Return to the directory


Q-96: What does the yield keyword do in Python?

The yield keyword converts any function into a generator. It works similar to the standard return keyword. But it always returns a generator object. In addition, a method can invoke the yield keyword multiple times.

See the following example.

def testgen(index) :
  weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri'.'sat']
  yield weekdays[index]
  yield weekdays[index+1]

day = testgen(0)
print next(day), next(day)

# output: sun mon
Copy the code

Return to the directory


Q-97: How do I convert a list to another data type?

Sometimes, we don’t use lists as they are. Instead, we must convert them to other types.

Converts a list to a string.

We can use the “.join() method to combine all elements into one and return them as a string.

weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri'.'sat']
listAsString = ' '.join(weekdays)
print(listAsString)

# Output: sun mon tue wed thu fri sat
Copy the code

Turns a list into a tuple.

The list is converted to a tuple by calling Python’s tuple() function.

This function takes a list as its argument.

But remember, we can’t change the list after making it into a tuple because it becomes immutable.

weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri'.'sat']
listAsTuple = tuple(weekdays)
print(listAsTuple)

# output: (' sun ', 'mon, tue, wed, thu,' fri ', 'sat)
Copy the code

Turn a list into a collection.

There are two side effects of turning a list into a collection.

  • The Set does not allow duplicate entries so that the transformation will remove any such items.
  • A collection is an ordered collection, so the order of the list items changes.

However, we can use the set() function to convert the list to a set.

weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri'.'sat'.'sun'.'tue']
listAsSet = set(weekdays)
print(listAsSet)

# output: set ([' wed ', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])
Copy the code

Turn the list into a dictionary.

In the dictionary, each entry represents a key-value pair. Therefore, converting lists is not as simple as converting other data types.

However, we can do this by splitting the list into pairs and then calling the zip() function to return them as tuples.

Passing tuples to the dict() function eventually turns them into dictionaries.

weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri']
listAsDict = dict(zip(weekdays[0: :2], weekdays[1: :2]))
print(listAsDict)

{'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}
Copy the code

Return to the directory


Q-98: How do you count the number of occurrences of each item in the list without explicitly mentioning it? Unlike a collection, a list can contain items with the same value.

In Python, lists have a count() function that returns the number of occurrences of a particular item.

Count the number of occurrences of a single item.

weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri'.'sun'.'mon'.'mon']
print(weekdays.count('mon'))

# Output: 3
Copy the code

Count the number of occurrences of each item in the list.

We will use the list derivation and the count() method. It will print the frequency of each item.

weekdays = ['sun'.'mon'.'tue'.'wed'.'thu'.'fri'.'sun'.'mon'.'mon']
print([[x,weekdays.count(x)] for x in set(weekdays)])

# output: [[' wed, 1], [' sun ', 2], [' thu, 1], [' tue, 1], [' mon, 3], [' fri, 1]]
Copy the code

Return to the directory


Q-99: What is NumPy and how is it better than lists in Python?

NumPy is a Python package for scientific computing that can handle large amounts of data. It includes a powerful n-dimensional array object and a set of high-level functions.

In addition, NumPy arrays are superior to built-in lists.

  • NumPy arrays are more compact than lists.
  • Reading and writing items using NumPy is faster.
  • Using NumPy is more convenient than using standard lists.
  • NumPy arrays are more efficient because they enhance the functionality of lists in Python.

Return to the directory


Q-100: What are the different ways to create an empty NumPy array in Python?

We can apply two methods to create an empty NumPy array.

The first way to create an empty array.

import numpy
numpy.array([])
Copy the code

The second method creates an empty array.

Create an empty array
numpy.empty(shape=(0.0))
Copy the code

Return to the directory


Summary – 100 basic Python interview questions

I’ve been writing a tech blog for a long time, and this is one of my interview questions to share. Hope you like it! Here is a summary of all my original and work source code:

Making, Gitee

Related articles:

  • 100 Basic Python Interview Questions Part 1 (1-20) | Python topic month
  • 100 Basic Python Interview Questions Part 2 (21-40) | Python topic month
  • 100 Basic Python Interview Questions Part 3 (41-60) | Python topic month
  • 100 Basic Python Interview Questions Part 4 (61-80) | Python topic month
  • 30 Python tutorials and tips | Python theme month

Recommended articles of the past:

  • Teach you to use Java to make a gobang game
  • Interesting way to talk about the history of JavaScript ⌛
  • The output of a Java program | Java exercises 】 【 7 sets (including parsing)
  • ❤️5 VS Code extensions that make refactoring easy ❤️
  • 140000 | 400 multichannel JavaScript 🎓 interview questions with answers 🌠 items (the fifth part 371-424)

If you do learn something new from this post, like it, bookmark it and share it with your friends. 🤗 Finally, don’t forget ❤ or 📑 for support