A novice Python programmer must know the basics of Python before seeking a job programming Python. The technical team at DataFlair has shared a collection of the most common Python interview questions of 2018. They range from basic Python interview questions to advanced Ones to guide you through your interview preparation, all with answers. The questions covered topics such as coding, data structures and scripting. This is the first article.
Q 1: What are the features and benefits of Python?
As an introductory programming language, Python has the following main features and advantages:
- Can explain
- Have dynamic characteristics
- object-oriented
- Clear and simple
- Open source
- Strong community support
In fact, of course, Python’s benefits go far beyond that. Read this document to learn more:
Stamp here
Q 2: What is the difference between a deep copy and a shallow copy?
A: A deep copy is copying one object into another. This means that if you make changes to a copy of an object, the original object will not be affected. In Python, we use the function deepcopy() to perform a deepcopy and import the module copy, as shown below:
>>> import copy
>>> b=copy.deepcopy(a)
Copy the code
>>> b=copy.copy(a)
Copy the code
Q 3. What is the difference between lists and tuples?
A: The main difference is that lists are mutable, while tuples are immutable. For example, look like this:
>>> 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
Copy the code
The following error will appear:
TypeError: ‘tuple’ object does not support item assignment
Copy the code
More on lists and tuples can be found here:
Stamp here
The questions from Q4 through Q20 are basic Python interview questions for beginners, but experienced people can also review the questions and review the basic concepts.
Q 4. Explain the ternary operators in Python
Unlike C++, which we don’t have in Python? :, but we have this:
[on true] if [expression] else [on false]
Copy the code
If the expression is True, the statement in [on True] is executed. Otherwise, the statement in [on false] is executed.
Here’s how to use it:
> > > a, b = 2, 3 > > > min = aif a<b else b
>>> min
Copy the code
Running result:
2
Copy the code
>>> print("Hi") if a<b else print("Bye")
Copy the code
Running result:
Hi
Copy the code
Q 5. How to implement multithreading in Python?
A thread is a lightweight process, and multithreading allows us to execute multiple threads at once. As we all know, Python is a multithreaded language and has a multithreaded toolkit built in.
The GIL (global interpreter lock) in Python ensures that a single thread is executed at once. One thread saves the GIL and performs some operations before passing it to the next thread, giving the illusion that we are running in parallel. But really, it’s just the threads taking turns running on the CPU. Of course, all this passing increases the memory pressure of the program execution.
Q 6. Explain inheritance in Python
When a class inherits from another class, it is said to be a subclass/derived class that inherits from its parent/base/superclass. It inherits/acquires all class members (properties and methods).
Inheritance allows us to reuse code and makes it easier to create and maintain applications. Python supports the following types of inheritance:
- Single inheritance: a class inherits from a single base class
- Multiple inheritance: One class inherits from multiple base classes
- Multi-level inheritance: a class inherits from a single base class, which in turn inherits from another base class
- Hierarchical inheritance: Multiple classes inherit from a single base class
- 2. The mixing of two or more types of inheritance. For more on inheritance, see:
Stamp here
Q 7. What is a Flask?
Flask is a lightweight Web application framework written in Python. The WSGI toolkit uses Werkzeug and the template engine uses Jinja2. Flask uses a BSD license. Two of these environment dependencies are Werkzeug and JinjA2, which means it does not need to rely on external libraries. For this reason, we call it a lightweight framework.
Flask sessions use signed cookies to allow users to view and modify the contents of the session. It records information from one request to another. However, in order to modify the session, the user must have the Flask. Secret_key key.
Q 8. How is memory managed in Python?
Python has a private heap space to hold all objects and data structures. As developers, we don’t have access to it; the interpreter manages it. But with the core API in place, we have access to some tools. The Python memory manager controls memory allocation.
In addition, the built-in garbage collector reclaims all unused memory, so make it suitable for heap space.
Q 9. Explain the help() and dir() functions in Python
The Help() function is a built-in function for viewing a detailed description of the function or module’s purpose:
>>> import copy
>>> help(copy.copy)
Copy the code
The running result is:
Help on function copy inModule copy: copy(x) Shallow copy operation on Arbitrary Python objects. See the module's __doc__ stringfor more info.
Copy the code
The Dir() function is also a built-in Python function. Without arguments, Dir() returns a list of variables, methods, and defined types in the current range. Returns a list of properties and methods with parameters.
The following example shows how dir can be used:
>>> dir(copy.copy)
Copy the code
The running result is:
[' __annotations__ ', '__call__', 'magic __class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__, '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', 'the.__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', 'the __str__', '__subclasshook__]Copy the code
Q 10. When exiting Python, do you free all memory?
The answer is No. Modules that loop around references to other objects or objects that reference from the global namespace are not completely freed when Python exits.
In addition, the memory reserved by the C library is not freed.
Q 11. What is a monkey patch?
Dynamically modifying a class or module at run time.
>>> class A:
def func(self):
print("Hi")
>>> def monkey(self):
print "Hi, monkey"
>>> m.A.func = monkey
>>> a = m.A()
>>> a.func()
Copy the code
The running result is:
Hi, Monkey
Copy the code
Q 12. What is a dictionary in Python?
A dictionary is something that doesn’t exist in programming languages like C++ and Java, and it has key-value pairs.
> > > roots = {let them therefore, as for, the deputies, 4-2, 1:1} > > >type(roots)
<class 'dict'>
>>> roots[9]
Copy the code
The running result is:
3
Copy the code
Dictionaries are immutable, and we can create them by a derivation.
>>> roots={x**2:x for x inRange (5, 0, 1)} > > > rootsCopy the code
Running result:
{25:5, 16:4, 9:3, 4:2, 1:1}Copy the code
Q 13. Please explain the use of *args and **kwargs
When we don’t know how many arguments to pass to a function, such as if we were passing a list or tuple, we use *args.
>>> def func(*args):
for i in args:
print(I) > > > func (3,2,1,4,7)Copy the code
The running result is:
3, 2, 1, 4, 7Copy the code
Use **kwargs to collect keyword arguments when we don’t know how many keyword arguments to pass.
>>> def func(**kwargs):
for i in kwargs:
print(i,kwargs[i])
>>> func(a=1,b=2,c=7)
Copy the code
The running result is:
a.1
b.2
c.7
Copy the code
Q 14. Write Python logic that counts 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)
Copy the code
Running result:
26
Copy the code
Q 15. What is a negative index?
Let’s create a list like this:
> > > mylist =,1,2,3,4,5,6,7,8 [0]Copy the code
A negative index, unlike a positive index, is retrieved from the right.
>>> mylist[-3]
Copy the code
Running result:
6
Copy the code
It can also be used for slices in a list:
>>> mylist[-6:-1]
Copy the code
Results:
[3, 4, 5, 6, 7]
Copy the code
Q 16. How do I scramble elements of a list in situ?
To do this, we import the shuffle() function from the random module.
>>> from random import shuffle
>>> shuffle(mylist)
>>> mylist
Copy the code
Running result:
[3, 4, 8, 0, 5, 7, 6, 2, 1]
Copy the code
Q 17. Explain Python’s join() and split() functions
Join() allows us to add specified characters to a string.
>>> ', '.join('12345')
Copy the code
Running result:
"1, 2, 3, 4, 5"Copy the code
Split() lets us Split a string with a specified character.
>>> '1, 2, 3, 4, 5'.split(', ')
Copy the code
Running result:
[' 1 ', '2', '3', '4', '5']Copy the code
Q 18. Is Python case sensitive?
If you can distinguish an identifier like myName from myName, then it is case sensitive. In other words, it cares a lot about uppercase and lowercase. We can try this in Python:
>>> myname='Ayushi'
>>> Myname
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
Copy the code
Running result:
Myname
NameError: name ‘Myname’ is not defined
Copy the code
As you can see, there is NameError, so Python is case sensitive.
Q 19. How long can identifiers in Python be?
In Python, identifiers can be of any length. In addition, we must follow the following rules when naming identifiers:
-
Must start with an underscore or A letter in a-z/A-Z
-
The rest can be a-Z/A-Z/ 0-9
-
Case sensitive
-
Keywords cannot be used as identifiers. Python has the following keywords:
Q 20. How to remove leading Spaces from a string?
Leading whitespace in a string is the space that appears before the first non-whitespace character in the string. We can remove it from the string using the method Istrip().
>>> ' Ayushi '.lstrip()
Copy the code
Results:
'Ayushi'Copy the code
As you can see, the string has both leading and suffix characters, and Istrip() is called to remove leading Spaces. If we want to remove suffix whitespace, use the rstrip() method.
>>> ' Ayushi '.rstrip()
Copy the code
Results:
'Ayushi'Copy the code
Questions Q 21 through Q 35 are advanced Python interview questions for those with Python experience.
Q 21. How do I convert a string to lowercase?
We use the lower() method.
>>> 'AyuShi'.lower()
Copy the code
Results:
'ayushi'Copy the code
You can convert it to uppercase using the upper() method.
>>> 'AyuShi'.upper()
Copy the code
Results:
'AYUSHI'Copy the code
Also, use the isupper() and islower() methods to check whether all characters are uppercase or lowercase.
>>> 'AyuShi'.isupper()
False
>>> 'AYUSHI'.isupper()
True
>>> 'ayushi'.islower()
True
>>> '@yu$hi'.islower()
True
>>> '@YU$HI'.isupper()
True
Copy the code
So, characters like @ and $satisfy both upper and lower case.
Istitle() tells us whether a string is in title format.
>>> 'The Corpse Bride'.istitle()
True
Copy the code
Q 22. What is a pass statement in Python?
When you’re writing code in Python, sometimes you haven’t figured out how to write the function, you’ve just written the function declaration, but in order to get the syntax right, you have to type something in. In this case, we use the pass statement.
>>> def func(*args):
pass
>>>
Copy the code
Also, the break statement allows us to break out of the loop.
>>> for i in range(7):
if i==3: break
print(i)
Copy the code
Results:
0
1
2
Copy the code
Finally, the continue statement allows us to skip to the next loop.
>>> for i in range(7):
if i==3: continue
print(i)
Copy the code
Results:
0, 1, 2, 4, 5, 6Copy the code
Q 23. What are closures in Python?
A nested function is a closure when it references a value in its outer region. The point is that this value will be recorded.
>>> def A(x):
def B():
print(x)
return B
>>> A(7)()
Copy the code
Results:
7
Copy the code
For more information on closures, see here:
Stamp here
Q 24. Explain the //, % and ** operators in Python
The // operator performs floor division, which returns the integer portion of the result.
> > > / / 2, 3, 7Copy the code
This will return 3.5.
Again, exponentials. Ab will return a to the b power.
> > > 2 * * 10, 1024Copy the code
Finally, % performs the mod operation, returning the remainder of the division.
>>> 13%7
6
>>> 3.5%1.5
0.5
Copy the code
Q 25. How many operators are there in Python? Explain the arithmetic operator.
In Python, we have seven operators: arithmetic, relational, assignment, logical, bitwise, member, and identity operators.
We have seven arithmetic operators that allow us to perform arithmetic operations on numeric values:
1. The plus sign (+) adds the two values
> > > 7 + 8 to 15Copy the code
2. The minus sign (-) subtracts the first value from the second
> > > 7-8-1Copy the code
3. Multiply (*), multiply the two values
> > > 7 * 8 56Copy the code
4. The division sign (/), divide the second value by the first value
>>> 7/8
0.875
>>> 1/1
1.0
Copy the code
5. Downward division, modulo and exponentiation operations, see the previous problem.
Q 26. Explain the relational operators in Python
Relational operators are used to compare two values.
1. The less than sign (<) returns True if the value on the left is smaller.
>>> 'hi'<'Hi'
False
Copy the code
2. The greater than sign (>) returns True if the value on the left is large.
> > > 1.1 + 2.2 > 3.3 TrueCopy the code
3. The less than or equal sign (<=) returns true if the value on the left is less than or equal to the value on the right.
> > > 3.0 < = 3 TrueCopy the code
4. The greater than or equal sign (>=) returns True if the value on the left is greater than or equal to the value on the right.
>>> True>=False
True
Copy the code
- The equals sign (==) returns True if both sides of the sign are equal.
> > >,3,2,2 {1} = = {1, 2, 3} TrueCopy the code
- Is not equal to the sign (! =), returns True if the values on both sides of the symbol are not equal.
>>> True! = 0.1 True > > > False! = 0.1 TrueCopy the code
Q 27. Explain the assignment operator in Python
This is an important interview question in a Python interview.
We show all the arithmetic operators and assignment symbols together:
> > > a = 7 > > > a + = 1 > > > a 8 > > > a - = 1 > > > a 7 > > > a * = 2 > > > a 14 > > > a / = 2 > > > a > 7.0 > > a * * = 2 > > > a 49 > > > a / / = 3 > > > 16.0 a >>> a%=4 >>> a 0.0Copy the code
Q 28. Explain logical operators in Python
Python has three logical operators: and, or, and not.
>>> False and True
False
>>> 7<7 or True
True
>>> not 2==2
False
Copy the code
Q 29. Explain member operators in Python
With the member operators’ in ‘and’ not in ‘, we can determine whether a value is a member of another value.
>>> 'me' in 'disappointment'
True
>>> 'us' not in 'disappointment'
True
Copy the code
Q 30. Explain the identity operators in Python
This is also a common question in Python interviews.
With the identity operators’ is’ and ‘is not’, we can verify that two values are the same.
>>> 10 is '10'
False
>>> True is not False
True
Copy the code
Q 31. Talk about bitwise operators in Python
The operator operates on values in bits.
- And (&), bitwise and operator: The two values involved in the operation, the result of which is 1 if both corresponding bits are 1, or 0 otherwise
>>> 0b110 & 0b010
2
Copy the code
(2) or (|), the bitwise or operator: as long as there is a corresponding two binary to 1, the result is 1.
> > > 3 | 2. 3Copy the code
3. Xor (^), bitwise Xor operator: When two corresponding binaries are different, the result is 1
> > > 3 ^ 2 to 1Copy the code
4. Invert (~), bitwise Invert operator: Invert each binary bit of data, that is, change 1 to 0, and change 0 to 1
> > > ~ 2-3Copy the code
5. Left displacement (<<) : all binary bits of the operand are shifted to the left by a number of bits. The digits to the right of << are specified
> > > 1 < < 2 4Copy the code
6. Right shift (>>) : shift all binary bits of the operand on the left of “>>” to the right by a number of digits
4 > > > > > 2 to 1Copy the code
For more information on operators, see here:
Stamp here
Q 32. How to use multibase numbers in Python?
In Python, we can use binary, octal, and hexadecimal in addition to decimal.
- Binary digits consist of zeros and ones, and we use the prefix 0b or 0b to represent binary numbers.
>>> int(0b1010)
10
Copy the code
2. Use the bin() function to convert a number to its binary form.
> > > bin (0 xf) '0 b1111'Copy the code
3. Octal numbers consist of the digits 0 to 7, with the prefix 0o or 0o to denote the base 8 number.
> > > oct (8) '0 o10'Copy the code
4. The hexadecimal number consists of digits 0 to 15. The prefix 0x or 0x indicates the hexadecimal number.
>>> hex(16) '0x10' >>> hex(15) '0xf'Copy the code
Q 33. How do I get a list of all the keys in the dictionary?
Use keys() to get all the keys in the dictionary
>>> mydict={'a': 1,'b': 2.'c': 3.'e':5}
>>> mydict.keys()
dict_keys(['a'.'b'.'c'.'e'])
Copy the code
Q 34. Why is it not recommended to start identifiers with an underscore
Because Python has no concept of private variables, the convention is to quickly declare a variable as private beginning with an underscore. So if you don’t want the variable to be private, don’t start with an underscore.
Q 35. How to declare and assign multiple variables?
There are two ways:
> > > a, b, c = three, four, five#This assigns 3, 4, and 5 to a, b, and c respectively
>>> a=b=c=3 #This assigns 3 to a, b, and c
Copy the code
Q 36. What is the decapsulation of tuples?
First let’s look at decapsulation:
Mytuple =3,4,5 >>> mytuple (3, 4,5)Copy the code
This encapsulates 3, 4, and 5 into the tuple mytuple.
Now we decapsulate these values into variables x, y, and z:
>>> x,y,z=mytuple
>>> x+y+z
Copy the code
So we get 12.
conclusion
These are some of the most common interview questions in Python and their answers. We will share more questions in the next article.