100 classic Python exercises pdf (with answers)

Posted by jacko310592 on Sun, 30 Jan 2022 22:23:05 +0100

A novice Python must be familiar with the basics of Python before seeking a job in Python programming. The technical team of DataFlair, a programming website, shared a collection of the most common Python interview questions, including both basic Python interview questions and advanced version questions to guide you in preparing for the interview, all of which are accompanied by answers. The interview questions include coding, data structure, script writing and other topics.

1: What are the features and advantages of Python?

A: as an introductory programming language, Python has the following characteristics and advantages:

Interpretable
With dynamic characteristics
object-oriented
Concise and simple
Open Source
Strong community support

2: What is the difference between a deep copy and a shallow copy?

A: deep copy is to copy an object to another object, which means that if you change the copy of an object, it will not affect the original object. In Python, we use the function deepcopy() to execute deep copy and import the module copy, as shown below:

>>> import copy
>>> b=copy.deepcopy(a)

Shallow copy is to copy the reference of one object to another, so if we change it in the copy, it will affect the original object. We use the function function() to perform a shallow copy as follows:

>>> b=copy.copy(a)
 

3. What is the difference between a list and a tuple?

A: the main difference between the two is that the list is variable and the tuple is immutable. An example is as follows:

>>> mylist=[1,3,3]
>>> mylist[1]=2
>>> mytuple=(1,3,3)
>>> mytuple[1]=2
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
mytuple[1]=2


 

The following error messages will appear:

TypeError: 'tuple' object does not support item assignment

More about lists and tuples can be found here:

From Q4 to Q20 are basic Python interview questions for novices, but experienced people can also take a look at these questions and review the basic concepts.

4. Explain the ternary operator in Python

Unlike C + +, we don't have?:, But we have this:

[on true] if [expression] else [on false]
 

If the expression is True, execute the statement in [on true]. Otherwise, execute the statement in [on false].
Here's how to use it:

>>> a,b=2,3
>>> min=a if a<b else b
>>> min


Operation result: 2

>>> print("Hi") if a<b else print("Bye")

Operation results:

Hi

5. How to implement multithreading in Python?

A thread is a lightweight process. Multithreading allows us to execute multiple threads at a time. As we all know, Python is a multi-threaded language with a built-in multi-threaded toolkit.

GIL (global interpreter lock) in Python ensures that a single thread is executed at a time. A thread saves GIL and performs some operations before passing it to the next thread, which will give us the illusion of running in parallel. But in fact, only threads run on the CPU in turn. Of course, all passing will increase the memory pressure of program execution.

6. Explain inheritance in Python

When a class inherits from another class, it is called a subclass / derived class, which inherits from the parent class / base class / superclass. It inherits / gets all class members (properties and methods).

Inheritance allows us to reuse code and make it easier to create and maintain applications. Python supports the following types of inheritance:
Single class inheritance: a class inherits from a single base class
Multiple inheritance: a class inherits from multiple base classes
Multi level inheritance: a class inherits from a single base class, which inherits from another base class
Hierarchical inheritance: multiple classes inherit from a single base class
Mixed inheritance: a mixture of two or more types of inheritance

7. What is Flask?

Flask is a lightweight Web application framework written in Python. Its WSGI toolbox uses Werkzeug, and the template engine uses jinja2. Flask uses BSD authorization. Two of these environment dependencies are Werkzeug and jinja2, which means that it does not need to rely on external libraries. For this reason, we call it lightweight framework.

Flash sessions use signature cookie s to allow users to view and modify session content. It records information from one request to another. However, to modify the session, the user must have the key flash secret_ key.

8. How is memory managed in Python?

Python has a private heap space to hold all objects and data structures. As developers, we can't access it. It's the interpreter that manages it. But with the core API, we can access some tools. Python memory manager controls memory allocation.

In addition, the built-in garbage collector recycles all unused memory, so it is suitable for heap space.

9. Explain the help() and dir() functions in Python

The Help() function is a built-in function used to view a detailed description of the purpose of a function or module:

>>> import copy
>>> help(copy.copy)


 

The operation result is:

Help on function copy in module copy:
copy(x)
 Shallow copy operation on arbitrary Python objects.
 See the module's __doc__ string for more info.

Dir() function is also a Python built-in function. When dir() function does not take parameters, it returns a list of variables, methods and defined types in the current range; With parameters, the list of properties and methods of the parameters is returned.

The following example shows how to use dir:

>>> dir(copy.copy)

The operation result is:

['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

10. When exiting Python, free all memory?

The answer is No. A module that circularly references other objects or objects from a global namespace is not completely released when Python exits.

In addition, the part of memory reserved by the C library will not be released.

11. What is a monkey patch?

Dynamically modify a class or module during runtime.

>>> class A:
    def func(self):
        print("Hi")
>>> def monkey(self):
print "Hi, monkey"
>>> m.A.func = monkey
>>> a = m.A()
>>> a.func()

The operation result is:

Hi, Monkey

12. What is the dictionary in Python?

Dictionary is something that is not found in programming languages such as C + + and Java. It has key value pairs.

>>> roots={25:5,16:4,9:3,4:2,1:1}
>>> type(roots)
<class 'dict'>
>>> roots[9]

The operation result is:

3

The dictionary is immutable, and we can also create it with a derivation. ​​​​​​​

>>> roots={x**2:x for x in range(5,0,-1)}
>>> roots

Operation results:

{25: 5, 16: 4, 9: 3, 4: 2, 1: 1}

13. Please explain the meaning of using args and * kwargs

When we don't know how many parameters to pass to the function, such as a list or tuple, we use * args.

>>> def func(*args):
    for i in args:
        print(i)  
>>> func(3,2,1,4,7)


 

The operation result is:

3
 
2
 
1
 
4
 
7

When we don't know how many keyword parameters to pass, we use * * kwargs to collect keyword parameters.

​​​​​​​>>> def func(**kwargs): for i in kwargs: print(i,kwargs[i])>>> func(a=1,b=2,c=7)

The operation result is:

a.1
 
b.2
 
c.7

14. Please write a Python logic to calculate the number of uppercase letters in a file
 

>>> import os
>>> os.chdir('C:\\Users\\lifei\\Desktop')
>>> with open('Today.txt') as today:
    count=0
    for i in today.read():
        if i.isupper():
            count+=1
print(count)

Operation results:

26

15. What is a negative index?

Let's create such a list first:

>>> mylist=[0,1,2,3,4,5,6,7,8]

Negative index is different from positive index. It starts from the right.

>>> mylist[-3]

Operation results:

6

It can also be used for slices in the list:

>>> mylist[-6:-1]

result:

[3, 4, 5, 6, 7]

16. How to disrupt the elements of a list by local operation?

To achieve this, we import the shuffle() function from the random module. ​​​​​​​

>>> from random import shuffle
>>> shuffle(mylist)
>>> mylist

Operation results:

[3, 4, 8, 0, 5, 7, 6, 2, 1]

17. Explain the join() and split() functions in Python

Join() allows us to add the specified character to the string.

>>> ','.join('12345')

Operation results:

'1,2,3,4,5'

Split() allows us to split strings with specified characters.

>>> '1,2,3,4,5'.split(',')

Operation results:

['1', '2', '3', '4', '5']

18. Is Python case sensitive?

If you can distinguish between identifiers like myname and myname, it is case sensitive. In other words, it cares about uppercase and lowercase. We can try Python:

>>> myname='Ayushi'
>>> Myname
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>


 

Operation results:

Myname

NameError: name 'Myname' is not defined

As you can see, NameError appears here, so Python is case sensitive.

19. How long can an identifier be in Python?

In Python, identifiers can be of any length. In addition, we must follow the following rules when naming identifiers:

You can only start with an underscore or a letter in A-Z/a-z
A-Z/a-z/0-9 can be used for the rest
Case sensitive
Keywords cannot be used as identifiers. Python has the following keywords:

image

20. How do I remove leading spaces from a string?

The leading space in a string is the space that appears before the first non space character in the string. We use the method Istrip() to remove it from the string.

>>> '   Ayushi '.lstrip()

result:

'Ayushi   '

You can see that the string has both leading characters and suffix characters. Calling Istrip() removes leading spaces. If we want to remove suffix spaces, we use the rstrip() method.

>>> '   Ayushi '.rstrip()

result:

'   Ayushi'

 

 

Topics: Python Back-end