Summary and analysis of surface python questions (a)

Q 1: What are the characteristics and advantages of Python have?

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

Interpretable

Dynamic nature

Object-Oriented

Concise simple

Open source

It has strong community support 

Of course, the advantages of Python is actually much more than that, you can read the documentation to learn more about:

https://data-flair.training/blogs/python-tutorial/ 

Q 2: The difference between deep and shallow copy copy what is?

A: deep copy is to copy one object to another object, which means that if you make a copy of an object change will not affect the original object. In Python, we use the function DeepCopy () perform a deep copy, Copy import module, as follows:

1>>> import copy

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

640?wx_fmt=jpeg

The shallow copy copy sucked an object reference to another object, so if we change the copy, will affect the original object. We use the function function () perform a shallow copy, use as follows:

1>>> b=copy.copy(a)

640?wx_fmt=jpeg

Q 3. The difference between lists and tuples are?

A: The main difference between the two is that lists are mutable, and tuples are immutable . For example, as shown below:

1>>> mylist=[1,3,3]

2>>> mylist[1]=2

3>>> mytuple=(1,3,3)

4>>> mytuple[1]=2

5Traceback (most recent call last):

6File "<pyshell#97>", line 1, in <module>

7mytuple[1]=2

You receive the following error:

1TypeError: ‘tuple’ object does not support item assignment

More details about lists and tuples, can be viewed here: 

https://data-flair.training/blogs/python-tuples-vs-lists/

From Q4 to Q20 are the basis for interview questions Python novices, but experienced people who can look at these issues, review the basic concepts.

Q 4. explain ternary operator in Python

Unlike C ++, we do not have in Python:?, But we have this:

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

If the expression is True, the implementation [on true] statements. Otherwise, execution [on false] statements.

Here is its methods: 

1>>> a,b=2,3

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

3>>> min

operation result: 

12

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

operation result:

1Hi

Q 5. How to implement multithreading in Python?

A thread is a lightweight process, multi-threaded execution allows us to once multiple threads. As we all know, Python is multi-threaded language, its built-in multithreaded tool kit.

In Python GIL (Global Interpreter Lock) to ensure the implementation of a single thread. GIL save a thread and pass it to perform some action before the next thread, which will enable us to produce the illusion of running in parallel. But in fact, just the thread turns running on the CPU. Of course, all of the memory transfer will increase the pressure of program execution.

Q 6. Explain inheritance in Python

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

Inheritance allows us to re-use code, but also easier to create and maintain applications. Python supports the following types of inheritance:

Single inheritance: single class inherits from a base class

Multiple inheritance: a plurality of class inherits from the base class

Multi-inheritance: single class inherits from a base class, which inherits from the base class to another 

Hierarchical inheritance: a plurality of single class inherits from the base class

Mixed Inheritance: Inheritance of two or more types of mixed

More details about inheritance, see:

https://data-flair.training/blogs/python-inheritance/ 

Q 7. What is the Flask?

Flask is a lightweight Web application framework written in Python. WSGI toolkit that uses Werkzeug, template engine is used Jinja2. Flask use BSD license. Two of the environment is dependent Werkzeug and jinja2, which means it does not need to rely on external libraries. For this reason, we call it a lightweight frame.

Flask session with the signature cookie allows users to view and modify the contents of the session. It will record the information to a request from another request. However, to modify the session, the user must have a key Flask.secret_key.

Q 8. In Python how to manage memory?

Python has a private heap space to hold all the objects and data structures. As developers, we can not access it, it is explained in management. But with the core API, we can access some tools. Python memory manager controls memory allocation.

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

help (Q 9. explained in Python) and dir () function

Help () function is a built-in function, or a function module for viewing purposes detailed description:

1>>> import copy

2>>> help(copy.copy)

Operating results as follows:

1Help on function copy in module copy:

2

3

4copy(x)

5

6Shallow copy operation on arbitrary Python objects.

7

8See the module’s __doc__ string for more info. 

Dir () function is also built-in functions Python, the dir () function when no arguments, return variable in the current scope, the type and method definitions list; when arguments, and returns the parameter attributes, list of methods. 

The following example demonstrates the use of dir:

1>>> dir(copy.copy)

Operating results as follows:

1[‘__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__’]

Q 10. When you exit Python, whether to release all the memory?

The answer is No. Circular references to other objects or references from objects in the global namespace of the module, not entirely freed when Python exits.

In addition, it will not release the memory part of the C library reserved .

Q 11. What is a monkey patch?

Dynamically modify a class or module during operation.

1>>> class A:

2    def func(self):

3        print("Hi")

4>>> def monkey(self):

5print "Hi, monkey"

6>>> m.A.func = monkey

7>>> a = m.A()

8>>> a.func()

Operating results as follows: 

1Hi, Monkey 

What are Q 12. Python in the dictionary?

Dictionary is C ++ and Java programming languages ​​that are not the things that have pairs.

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

2>>> type(roots)

3<class 'dict'>

4>>> roots[9]

Operating results as follows:

13

Dictionary is immutable, we can derive a formula to create it.

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

2>>> roots

operation result:

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

Q 13. Please explain the use * args and ** kwargs meaning

When we do not know how many parameters are passed to a function, such as we have to pass a list or tuple, we use the * args.

1>>> def func(*args):

2    for i in args:

3        print(i) 

4>>> func(3,2,1,4,7) 

Operating results as follows:

13

2

32

4

51

6

74

8

97

When we do not know how many keyword arguments that pass, use ** kwargs to collect keyword arguments.

1>>> def func(**kwargs):

2    for i in kwargs:

3        print(i,kwargs[i])

4>>> func(a=1,b=2,c=7)

Operating results as follows:

1A.1

2

3b.2

4

5c.7

Q 14. Please write a logical Python, calculate the number of capital letters in a document

1>>> import os

2

3>>> os.chdir('C:\\Users\\lifei\\Desktop')

4>>> with open('Today.txt') as today:

5    count=0

6    for i in today.read():

7        if i.isupper():

8            count+=1

9print(count)

operation result:

126

Q 15. What is the negative index?

We create such a list:

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

Negative and positive index index is different, it is beginning to retrieve from the right.

1>>> mylist[-3] 

operation result:

16

It can also be used to slice the list: 

1>>> mylist[-6:-1]

result:

1[3, 4, 5, 6, 7]

 Q 16. How in situ operation to disrupt elements of a list?

To this end, we introduced shuffle () function from the random module.

1>>> from random import shuffle

2>>> shuffle(mylist)

3>>> mylist

operation result:

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

Q 17. explained in Python join () and split () function

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

2

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

operation result:

1‘1,2,3,4,5’

Split () allows us to split the string with the specified characters.

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

operation result:

1[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

Q 18. Python is case sensitive it?

If you can distinguish between such identifiers like myname and Myname, then it is case-sensitive. That it cares about upper and lower case. We can use Python to try:

1>>> myname='Ayushi'

2>>> Myname

3Traceback (most recent call last):

4File "<pyshell#3>", line 1, in <module>

operation result:

1Myname

2NameError: name ‘Myname’ is not defined

It can be seen here appeared NameError, so Python is case-sensitive.

Q 19. Python identifier length in the can how long?

In Python, the identifier may be any length. In addition, we must abide by the following rules for naming identifiers Shihai:

Can only begin with an underscore or AZ / az letters

The rest can be used AZ / az / 0-9

Case sensitive

Keywords can not be used as identifiers, Python There are the following keywords:

Q 20. how to remove leading spaces in a string?

Leading spaces in the string is a space before the first non-space character in the string appears. We use Istrip () which can be removed from the string.

1>>> '   Ayushi '.lstrip()

result:

1'Ayushi '

It can be seen that both the leading character string, there suffix character, calling Istrip () removes leading spaces. If we want to remove the trailing spaces, use rstrip () method.

1>>> '   Ayushi '.rstrip()

result:

1 'Ayushi'

From Q 21 to Q 35 it is ready to have Python experience advanced version of Python interview questions.

Q 21. How to convert a string to lowercase? 

We use lower () method. 

1>>> 'AyuShi'.lower()

result: 

1'ayushi ' 

Use upper () method may be converted to uppercase. 

1>>> 'AyuShi'.upper()

result:

1'AYUSHI '

In addition, isupper () and islower () method checks whether the string are all lowercase or uppercase.

1>>> 'AyuShi'.isupper()

2False

3

4>>> 'AYUSHI'.isupper()

5True

6

7>>> 'ayushi'.islower()

8True

9

10>>> '@yu$hi'.islower()

11True

12

13>>> '@YU$HI'.isupper()

14True

So, this character like @ and $ satisfy both uppercase lowercase meet.

Istitle () can tell us whether a string to title.

1>>> 'The Corpse Bride'.istitle()

2True

What are Q 22. Python in a pass statement?

When writing code in Python, sometimes you have not figured out how to write a function, just write a function declaration, but in order to ensure the correct syntax, you must type something, in this case, we will use the pass statement.

1 >>> def func(*args):

2           pass

3>>>

Similarly, BREAK statement let us out of the loop.

1>>> for i in range(7):

2    if i==3: break

3print(i)

result:

10

2

31

4

52

Finally, the Continue statement allow us to skip to the next cycle.

1>>> for i in range(7):

2    if i==3: continue

3print(i) 

result: 

10

2

31

4

52

6

74

8

95

10

116 

What are Q 23. Python closures that?

When a nested function references a value in its outer region, the nested function is a closure. Its meaning is will record the value.

1>>> def A(x):

2    def B():

3        print(x)

4    return B

5>>> A(7)()

result:

17 

More about closures, see here:

https://data-flair.training/blogs/python-closure/

** Q 24. // explain the Python, and **% ** operator

1 // operator performs division floor (round down divisible), it returns the integer portion of the result is divisible.

2

3>>> 7//2

43

It will return here after divisible 3.5.

Similarly, performs exponentiation operation. ab returns a power of b.

1>>> 2**10

21024

Finally,% executed modulo operation returns the remainder of the division. 

1>>> 13%7

26

3>>> 3.5%1.5

40.5

Q 24. How many operators have in Python? Explain arithmetic operators.

In Python, we have seven kinds of operators: arithmetic operators, relational operators, assignment operators, logical operators, bit operators, members of the operators, the identity of the operator.

We have seven arithmetic, allowed us to arithmetic operation values:

1. The plus sign (+), the two values

1>>> 7+8

215

2. The minus sign (-), the first value by subtracting the second value 

1>>> 7-8

2-1

3. multiplication (*), multiplying the two values

1>>> 7*8

256

No. 4. In addition to (/), by dividing the first value by the second value 

1>>> 7/8

20.875

3>>> 1/1

41.0

5. divisible taken down, and the modulo exponentiation arithmetic, see the previous question.

Q 25. explain Python relational operators

 

Relational operators used to compare two values.

1. less than (<), if the value of the left is small, the return True. 

1>>> 'hi'<'Hi'

2False

2. greater than (>), if the left side value is large, the return True.

1>>> 1.1+2.2>3.3

2True 

3. The number less than or equal (<=), if the value is less than or equal to the left of the right, is returned Ture.

1>>> 3.0<=3

2True

4 greater than or equal to (> =), if the value is greater than or equal to left right, True is returned.

1>>> True>=False

2True 

Equal sign (==), if the value of the symbol on both sides are equal, returns True.

1>>> {1,3,2,2}=={1,2,3}

2True

Number is not equal (! =), If the value is not equal on both sides of the symbol, True is returned.

1>>> True!=0.1

2True

3>>> False!=0.1

4True 

Q 26. explain the assignment operator Python

This is an important interview questions in Python interview.

We will all arithmetic operators and assignment symbol on the show together:

1>>> a=7

2>>> a+=1

3>>> a

48

5

6>>> a-=1

7>>> a

87

9

10>>> a*=2

11>>> a

1214

13

14>>> a/=2

15>>> a

167.0

17

18>>> a**=2

19>>> a

2049

21

22>>> a//=3

23>>> a

2416.0

25

26>>> a%=4

27>>> a

280.0

Q 27. explain the logical operators in Python

Python, the three logical operators: and, or, not.

1>>> False and True

2False

3

4>>> 7<7 or True

5True

6

7>>> not 2==2

8False

Q 28. explain in Python member operator

By members of the operators 'in' and 'not in', we can confirm whether a value is a member of another value.

1>>> 'me' in 'disappointment'

2True

3

4>>> 'us' not in 'disappointment'

5True

Q 29. Explain the identity operator in Python

It is also an interview in Python often asked questions.

Identity by the operator 'is' and 'is not', we can confirm that the two values ​​are the same.

1>>> 10 is '10'

2False

3

4>>> True is not False

5True

Q 30. talk bitwise operators in Python

The operator of the corresponding bits of the operation values. 

And (&), bitwise AND operator: involved in computing two values, if the corresponding two bits are 1, then the 1-bit result is 0 otherwise

1>>> 0b110 & 0b010

22

Or 2. (|), or bitwise operators: two long as the corresponding binary bit is a 1, it is a result bit.

1>>> 3|2

23

3

3. XOR (^), bitwise exclusive OR operator: When two different corresponding binary, the result is a

1>>> 3^2

21 

4. negated (-), bitwise operators: for each binary data bit inverse, i.e., the 1 to 0, the 0 to 1

1>>> ~2

2-3 

5. Left shifts (<<), each binary operand to the left a number of bits of all, the number to the right the number of bits specified << movement, discarding high, 0 low fill

1>>> 1<<2

24

6. The right shift (>>), the respective binary operand is ">>" All right a number of bits on the left, a specified number of bits to the right >> moved

1>>> 4>>2

21

For more information on operators, the reference here:

https://data-flair.training/blogs/python-operators/

Q 31. How to use the multi-value digital in Python?

We Python, also can be used in addition to the decimal binary, octal and hexadecimal.

The binary digits 0 and 1, we use the 0b or 0B prefix indicates a binary number.

1>>> int(0b1010)

210

2. bin () function to convert a number to its binary form.

1>>> bin(0xf)

2‘0b1111’

3. 0-7 octal digital form, that the octal number with the prefix 0o or 0O.

1>>> oct(8)

2'0o10 '

4. hexadecimal number composed by the numeral 0-15 indicates a hexadecimal number with the prefix 0x or 0X.

1>>> hex(16)

2‘0x10’

3

4>>> hex(15)

5‘0xf’

Q 32. How to get a list of all the keys of the dictionary?

Use keys () Gets all the keys dictionary 

1>>> mydict={'a':1,'b':2,'c':3,'e':5}

2>>> mydict.keys()

3dict_keys(['a', 'b', 'c', 'e'])

Q 33. Why is not recommended to start with an underscore as an identifier

Because Python and no concept of private variables, so quick to underline the beginning of the convention to declare a variable as private. So if you do not want private variables, do not use leading underscores.

Q 34. How to declare multiple variables and assignment?

There are two ways:

1>>> a,b,c=3,4,5 #This assigns 3, 4, and 5 to a, b, and c respectively

2>>> a=b=c=3 #This assigns 3 to a, b, and c

Q 35. What decapsulation tuple is?

First we look at de-encapsulation:

1>>> mytuple=3,4,5

2>>> mytuple

3(3, 4, 5)

This package will 3,4,5 tuple in mytuple.

We will now decapsulates these values ​​to variables x, y, z in which: 

1>>> x,y,z=mytuple

2>>> x+y+z

12 get results. 

Epilogue

These are the Python interview some common questions and answers.

Guess you like

Origin www.cnblogs.com/zhangyang520/p/11621831.html