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

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-61: How do I assign a Class attribute at run time?

We can specify the value of the property at run time. We need to add an init method and pass the input to the object constructor. See the following example to illustrate this.

>>> class Human:
    def __init__(self, profession) :
        self.profession = profession
    def set_profession(self, new_profession) :
        self.profession = new_profession

>>> man = Human("Manager")
>>> print(man.profession)
Manager
Copy the code

Return to the directory


Q-62: What is inheritance in Python programming?

Inheritance is an OOP mechanism that allows an object to access the functions of its parent class. It passes base class functionality to the child.

We deliberately abstracted similar code from different classes.

The common code is in the base class, which can be accessed by subclass objects through inheritance. Take a look at the following example.

class PC: # Base class
    processor = "Xeon" # Common attribute
    def set_processor(self, new_processor) :
        processor = new_processor

class Desktop(PC) : # Derived class
    os = "Mac OS High Sierra" # Personalized attribute
    ram = "32 GB"

class Laptop(PC) : # Derived class
    os = "Windows 10 Pro 64" # Personalized attribute
    ram = "16 GB"

desk = Desktop()
print(desk.processor, desk.os, desk.ram)

lap = Laptop()
print(lap.processor, lap.os, lap.ram)
Copy the code

Output:

Xeon Mac OS High Sierra 32 GB
Xeon Windows 10 Pro 64 16 GB
Copy the code

Return to the directory


Q-63: What is a combination in Python?

Composition is also an inheritance in Python. It is intended to inherit from the base class, but a little differently, by using instance variables of the base class as members of the derived class.

See below.

To demonstrate composition, we need to instantiate other objects in the class and then use those instances.

class PC: # Base class
    processor = "Xeon" # Common attribute
    def __init__(self, processor, ram) :
        self.processor = processor
        self.ram = ram

    def set_processor(self, new_processor) :
        processor = new_processor

    def get_PC(self) :
        return "%s cpu & %s ram" % (self.processor, self.ram)

class Tablet() :
    make = "Intel"
    def __init__(self, processor, ram, make) :
        self.PC = PC(processor, ram) # Composition
        self.make = make

    def get_Tablet(self) :
        return "Tablet with %s CPU & %s ram by %s" % (self.PC.processor, self.PC.ram, self.make)

if __name__ == "__main__":
    tab = Tablet("i7"."16 GB"."Intel")
    print(tab.get_Tablet())
Copy the code

The output is:

Tablet with i7 CPU & 16 GB ram by Intel
Copy the code

Return to the directory


Q-64: What are errors and exceptions in Python programs?

An error is a coding problem in a program that can cause it to exit abnormally.

Instead, an exception occurs when an external event occurs that interrupts the normal flow of a program.

Return to the directory


Q-65: How do you use Try/Except/Finally to handle exceptions in Python?

Python has a Try, Except, and Finally structure to handle errors and exceptions. We enclose the indented unsafe code under the try block. We can keep the fallback code in the except block. Any instruction intended to be executed last should be under the finally block.

try:
    print("Executing code in the try block")
    print(exception)
except:
    print("Entering in the except block")
finally:
    print("Reached to the final block")
Copy the code

The output is:

Executing code in the try block
Entering in the except block
Reached to the final block
Copy the code

Return to the directory


Q-66: How do you throw exceptions for predefined conditions in Python?

We can throw exceptions based on certain conditions.

For example, if we want the user to enter only odd numbers, an exception will be thrown otherwise.

# Example - Raise an exception
while True:
    try:
        value = int(input("Enter an odd number- "))
        if value%2= =0:
            raise ValueError("Exited due to invalid input!!!")
        else:
            print("Value entered is : %s" % value)
    except ValueError as ex:
        print(ex)
        break
Copy the code

The output is:

Enter an odd number- 2
Exited due to invalid input!!!!!!!!!Copy the code
Enter an odd number- 1
Value entered is : 1
Enter an odd number-
Copy the code

Return to the directory


Q-67: What is a Python iterator?

Iterators in Python are array-like objects that allow you to move over the next element. We use them when traversing a loop, such as in a “for” loop.

There is no Python library. Iterator for. For example, if a list is also an iterator, we can start a for loop on it.

Return to the directory


Q-68: What’s the difference between an Iterator and an Iterable?

Collection types such as lists, tuples, dictionaries, and collections are all iterable objects, and they are also iterable containers that return iterators on traversal.

Return to the directory


Here are some advanced Python interview questions.

Q-69: What is a Python generator?

A Generator is a function that lets us specify a function that acts like an iterator and can therefore be used within a “for” loop.

In generator functions, the yield keyword replaces the return statement.

# Simple Python function
def fn() :
    return "Simple Python function."

# Python Generator function
def generate() :
    yield "Python Generator function."

print(next(generate()))
Copy the code

The output is:

Python Generator function.
Copy the code

Return to the directory


Q-70: What are closures in Python?

A Python closure is a function object returned by another function. We use them to eliminate code redundancy.

In the following example, we write a simple multiplication closure.

def multiply_number(num) :
    def product(number) :
        'product() here is a closure'
        return num * number
    return product

num_2 = multiply_number(2)
print(num_2(11))
print(num_2(24))

num_6 = multiply_number(6)
print(num_6(1))
Copy the code

The output is:

22
48
6
Copy the code

Return to the directory


Q-71: What are decorators in Python?

Python decorators enable us to dynamically add new behavior to a given object. In the following example, we have written a simple example to show messages before and after a function is executed.

def decorator_sample(func) :
    def decorator_hook(*args, **kwargs) :
        print("Before the function call")
        result = func(*args, **kwargs)
        print("After the function call")
        return result
    return decorator_hook

@decorator_sample
def product(x, y) :
    "Function to multiply two numbers."
    return x * y

print(product(3.3))
Copy the code

The output is:

Before the function call
After the function call
9
Copy the code

Return to the directory


Q-72: How do you create a dictionary in Python?

Let’s take construction site statistics. To do this, we first need to split the key-value pair using a colon (” : “). The key should be immutable, that is, we will use data types that are not allowed to change at run time. We will choose from integers, strings, or tuples.

However, we can take any type of value. To distinguish data pairs, we can use commas (“, “) and leave the entire content in curly braces ({… }).

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> type(site_stats)
<class 'dict'> > > >print(site_stats)
{'type': 'organic'.'site': 'tecbeamers.com'.'traffic': 10000}
Copy the code

Return to the directory


Q-73: How do you read a dictionary in Python?

To get data from the dictionary, we can access it directly using keys. We can use square brackets […] after mentioning the variable name corresponding to the dictionary. Enclose “key”.

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> print(site_stats["traffic"])
Copy the code

We can even call the get method to get the value from the dictionary. It also lets us set a default value. If the key is missing, a KeyError occurs.

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> print(site_stats.get('site'))
tecbeamers.com
Copy the code

Return to the directory


Q-74: How do I iterate over dictionary objects in Python?

We can use the “for” and “in” loops to traverse the dictionary object.

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> for k, v in site_stats.items():
    print("The key is: %s" % k)
    print("The value is: %s" % v)
    print("+ + + + + + + + + + + + + + + + + + + + + + + +")
Copy the code

The output is:

The key is: type
The value is: organic
++++++++++++++++++++++++
The key is: site
The value is: tecbeamers.com
++++++++++++++++++++++++
The key is: traffic
The value is: 10000
++++++++++++++++++++++++
Copy the code

Return to the directory


Q-75: How do you add elements to a dictionary in Python?

We can add elements by modifying the dictionary with a new key and then setting values for them.

>>> # Setup a blank dictionary
>>> site_stats = {}
>>> site_stats['site'] = 'google.com'
>>> site_stats['traffic'] = 10000000000
>>> site_stats['type'] = 'Referral'
>>> print(site_stats)
{'type': 'Referral'.'site': 'google.com'.'traffic': 10000000000}
Copy the code

We can even connect two dictionaries with the help of the update() method to get a larger dictionary.

>>> site_stats['site'] = 'google.co.in'
>>> print(site_stats)
{'site': 'google.co.in'}
>>> site_stats_new = {'traffic': 1000000."type": "social media"}
>>> site_stats.update(site_stats_new)
>>> print(site_stats)
{'type': 'social media'.'site': 'google.co.in'.'traffic': 1000000}
Copy the code

Return to the directory


Q-76: How do I remove elements of a dictionary in Python?

We can remove keys from the dictionary using the del() method.

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> del site_stats["type"]
>>> print(site_stats)
{'site': 'google.co.in'.'traffic': 1000000}
Copy the code

Another method we can use is the pop() function. It takes a key as an argument. In addition, the second argument, if the key does not exist, we can pass a default value.

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> print(site_stats.pop("type".None))
organic
>>> print(site_stats)
{'site': 'tecbeamers.com'.'traffic': 10000}
Copy the code

Return to the directory


Q-77: How do you check for the presence of keys in a dictionary?

We can use Python’s “in” operator to test for the presence of keys in dict objects.

>>> site_stats = {'site': 'tecbeamers.com'.'traffic': 10000."type": "organic"}
>>> 'site' in site_stats
True
>>> 'traffic' in site_stats
True
>>> "type" in site_stats
True
Copy the code

Earlier, Python also provided the deprecated has_key() method.

Return to the directory


Q-78: What is the syntax for a list derivation in Python?

The list derivation is signed as follows:

[ expression(var) for var in iterable ]
Copy the code

For example, the following code returns all the numbers from 10 to 20 and stores them in a list.

>>> alist = [var for var in range(10.20)]
>>> print(alist)
Copy the code

Return to the directory


Q-79: What is the syntax for dictionary understanding in Python?

The syntax of a dictionary is the same as that of a list derivation, except that it uses braces:

{ aKey, itsValue for aKey in iterable }
Copy the code

For example, the following code returns all the numbers 10 through 20 as keys and stores the corresponding squares of those numbers as values.

>>> adict = {var:var**2 for var in range(10.20)}
>>> print(adict)
Copy the code

Return to the directory


Q-80: What is the syntax for generator expressions in Python?

The syntax of a generator expression matches that of a list derivation, but differs in that it uses parentheses:

( expression(var) for var in iterable )
Copy the code

(Expression (var) for var in iterable) For example, the following code will create a generator object that generates values of 10 to 20 when used.

>>> (var for var in range(10.20))
 at 0x0000000003668728>
>>> list((var for var in range(10.20)))
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
  • 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