In-depth answers to 11 basic questions about Python and 11 on python11

Source: Internet
Author: User

In-depth answers to 11 basic questions about Python and 11 on python11

Preface

This article gives you an in-depth answer to the 11 basic questions about Python. Through these questions, you can further understand and learn about python. Let's not talk about them here. Let's take a look at the detailed introduction.

I. single quotation marks, double quotation marks, and three quotation marks

Describe the scenarios and differences of the three quotation marks respectively

1) single quotes and double quotes are mainly used to represent strings.

For example:

  • Single quotes: 'python'
  • Double quotation marks: "python"

2). Three quotation marks

  • Three single quotes: '''python'. It can also indicate that a string is generally used to input multiple lines of text or to annotate a large segment.
  • Double quotation marks: "python" is generally used in the class to comment the class. In this way, you can use the Class Object _ doc _ to access the document.

Differences:

If your string contains single quotes, you must use double quotation marks.

For example:"can't find the log\n"

Ii. Whether to pass a value or a reference through Python Parameters

The following is an example of how to pass Python function parameters.

1). Python parameters are passed as follows:

Location parameters

Default parameter,

Variable parameters,

Keyword Parameter

2) whether the value passed by the function is value transfer or reference transfer depends on the situation

A. Immutable parameters are passed with values:

Immutable objects such as integers and strings are transmitted through copying, because you cannot change immutable objects in the original place in any way.

B. variable parameters are passed by reference.

For example, objects like lists and dictionaries are passed through references, which is similar to passing arrays with pointers in C language. variable objects can be changed within the function.

3. What is a lambda function? What are its advantages?

Demonstrate lambda usage and demonstrate the advantages of using lambda

1). lambda usage:

Lambda is an anonymous function. Its usage is as follows:lambda arg1,arg2..argN:expression using args

2). Advantages

Lambda can do the same kind of work as def, especially for those simple logic functions, directly using lambda is more concise, and saves the trouble of getting the function name (naming a function is a technical task)

Iv. String formatting: difference between % and. format

The format function of a string is very flexible and powerful. There are no limits on acceptable parameters, and the positions can be unordered, and there are more powerful format delimiters (such as filling, alignment, precision)

5. How does Python perform memory management?

1). Object reference counting mechanism

Python uses reference counting internally to keep track of objects in memory. All objects have reference counting.

Increase in reference count:

  • Assign a new name to an object
  • Put it into a container (such as a list, tuples, or dictionary)

When the reference count is reduced:

  • Destroy the display of the object alias using the del statement
  • Reference is out of scope or assigned again

2). Garbage Collection

When the reference count of an object is zero, it will be disposed of by the garbage collection mechanism.

3). Memory Pool Mechanism

Python provides a garbage collection mechanism for memory, but it puts unused memory into the memory pool instead of returning it to the operating system:

  • Pymalloc mechanism: To accelerate the execution efficiency of Python, Python introduces a memory pool mechanism to manage the application and release of small memory blocks.
  • Python objects, such as integers, floating-point numbers, and lists, all have their own private memory pools, and objects do not share their memory pools. That is to say, if you allocate and release a large number of integers, the memory used to cache these integers cannot be distributed to floating point numbers.

6. Write a function, input a string, and return the result of inverted sorting.

Input:string_reverse(‘abcdef'), Return: 'CBA Ba', write out multiple methods you can think

1). Use the character string to flip

def string_reverse1(text='abcdef'):return text[::-1]

2) convert the string into a list using the reverse function of the list.

3) create a new list from the back

4). Use the extendleft function in the deque bidirectional list

5) Recursion

7. Merge the following two lists in ascending order and remove duplicate elements.

list1 = [2, 3, 8, 4, 9, 5, 6]list2 = [5, 6, 10, 17, 11, 2]

1). the simplest method is to use set

list3=list1+list2print set(list3)

2) Recursion

Select an intermediate number, then a small number and a large number at one side, and then recycle and recursion to sort out the order (remember the bubbles in c)

8. What is the output of the following code? Give your answer and explain

class Parent(object): x = 1class Child1(Parent): passclass Child2(Parent): passprint Parent.x, Child1.x, Child2.xChild1.x = 2print Parent.x, Child1.x, Child2.xParent.x = 3print Parent.x, Child1.x, Child2.x>>1 1 11 2 13 2 3

Answer:

What makes you confused or surprised is that the output of the last row is 3 2 3 rather than 3 2 1. Why does the value of Parent. x change the value of Child2.x, but the value of Child1.x does not change at the same time?

The key to this answer is that in Python, class variables are internally processed as dictionaries. If the name of a variable is not found in the dictionary of the current class, the ancestor class (such as the parent class) will be searched until the referenced variable name is found.

  • First, setting x = 1 in the parent class makes the value of class variable x in referencing the class and any of its subclasses 1. This is because the output of the first print statement is 1 1 1.
  • Then, if any of its child classes overwrites this value (for example, we execute the statementChild1.x = 2) This value is only changed in the subclass. This is why the output of the second print statement is 1 2 1.
  • Finally, if the value is changed in the parent class (for example, we execute the statementParent.x = 3), This change will affect the value of any subclass that has not overwritten this value (in this example, the affected subclass is Child2 ). This is why the third print output is 3 2 3

9. Will the following code return an error?

list = ['a', 'b', 'c', 'd', 'e']print list[10:]

No error is reported, and a [] is output, and no IndexError is returned.

Answer:

When you try to access a member that exceeds the list index value, IndexError will occur (for example, access the list [10] of the above list). However, slice that tries to access a list starting with an index that exceeds the length of the list will not cause IndexError and will only return an empty list

A nasty small problem is that it causes bugs and is difficult to trace, because it does not cause errors during running and vomit blood ~~

10. output values of list1, list2, and list3 below

def extendList(val, list=[]): list.append(val) return listlist1 = extendList(10)list2 = extendList(123,[])list3 = extendList('a')print "list1 = %s" % list1print "list2 = %s" % list2print "list3 = %s" % list3>>list1 = [10, 'a']list2 = [123]list3 = [10, 'a']

Many people mistakenly think that list1 should be equal to [10] And list3 should be equal to ['a']. It is believed that the list parameter will be set to its default value [] each time extendList is called.

However, what actually happens is that the new default list is only created once when the function is defined. When extendList is not called by the specified list parameter, it uses the same list. This is why when a function is defined, the expression is calculated using the default parameter, rather than called.

Therefore, list1 and list3 are the same list of operations. While list2 is an independent list created by the operator (by passing its own empty list as the value of the list parameter)

Therefore, you must remember to set the list to None to avoid any problems.

11. write the code that you think is the most Pythonic.

Pythonic programming style is a pursuit of Python. The essence is the pursuit of intuitive, concise and easy to read.

Below are some good examples

1). Interaction Variables

Non-Pythonic

temp = aa = bb = temppythonic:a,b=b,a

2) Determine whether the value is true or false

Name = 'Tim 'langs = ['as3', 'lua', 'C'] info = {'name': 'time', 'sex': 'male ', 'age': 23} non-Pythonicif name! = ''And len (langs)> 0 and info! = {}: Print ('all True! ') Pythonic: if name and langs and info: print ('all True! ')

3) List Derivation

[x for x in range(1,100) if x%2==0]

Create a key-Value Pair in 42.16.zip

keys = ['Name', 'Sex', 'Age']values = ['Jack', 'Male', 23]dict(zip(keys,values))

Pythonic has a lot of code. Here are some typical examples.

Summary

The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.