程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[continuous update...] Special topic of Niuke Python

編輯:Python

1. [str] stay Python3 in , The operation result of the string is :

strs = 'I like python and java'
one = strs.find('n')
print(one)
two = strs.rfind('n')
print(two)
  • 12,12
  • 15,15
  • 12,15
  • None,None

find It's from the past to the future , Returns the position index of the first character successfully matched
rfind Also looking from the front to the back , But back to The last successful match Position index of the character of

2. [open] Which of the following code reads a file correctly ?

  • f = open(“test.txt”, “read”)
  • f = open(“r”,“test.txt”)
  • f = open(“test.txt”, “r”)
  • f = open(“read”,“test.txt”)

Python in , The syntax of opening the file is text = oepn(filePath, Mode of operation , Encoding mode )
Common operation modes :

  • ‘r’: read
  • ‘w’: Write
  • ‘a’: Additional
    Common coding methods :
  • utf-8
  • gbk

3. [list] stay Python3 in , The correct procedure for the following is :

lists = [1, 2, 3, 4, 5, 6]
print(lists[6:])
  • Report errors
  • []
  • [1,2,3,4,5,6]
  • [6]

Pay attention to distinguish slices , Slicing generally refers to creating new objects , Once the slice value of the slice created based on the original list exceeds the index subscript of the original list, it will not be able to get elements from the original list , Therefore, an empty subscript is returned
Slices are light copies , No index is out of bounds

4. python The search order of variables is ()

  • Local scope > External nested scope > Global scope > Built in module scope
  • External nested scope > Local scope > Global scope > Built in module scope
  • Built in module scope > Local scope > External nested scope > Global scope
  • Built in module scope > External nested scope > Local scope > Global scope

Python The scope of variables follows LEGB principle , namely

  • L:Local, Local scope , That is, the variables we define in the function ;
  • E:Enclosing, The local scope of the nested parent function , That is, the local scope of the parent function containing this function , But it's not the whole thing ;
  • G:Globa, Global variables , Variables defined at the module level ;
  • B:Built-in, Variables in the built-in module of the system , such as int, bytearray etc. .

5. [ Scope ] Perform the following procedure , The output is ()

a = [1]
b = 2
c = 1
def fn(lis, obj):
lis.append(b)
obj = obj + 1
return lis, obj
fn(a, c)
print(fn(a, c))
  • ([1, 2, 2], 2)
  • ([1, 2, 2], 3)
  • ([1, 2], 2)
  • ([1, 2], 3)

fn(a,c): Called once fn function , Now a Turned into [1,2],c still 1, Because although the function returns obj, But there's no assignment , After the function comes out c Or the global variable c;
print(fn(a,c)): Again fn function , The process is the same as above , But when printing, the return value of the function is printed , That is, the formal parameter at this time lis and obj Value , And then lis yes [1,2,2], and obj yes 2.

6. [ Logical operators ] python3 in , perform not 1 and 1 As the result of the

  • True
  • False
  • 0
  • 1

stay Python3 in ,not Express logical not ,and Representation logic and , Logic is not (not) The operation priority of is greater than that of logical and (and) The priority of the , be not 1 by False, be not 1 and 1 The result is False
priority not>and>or, homophonic not at all
not 1 = False
False and 1 = False

7. [str] stay Python3 The running result of the following string program in is ?

str1 = "exam is a example!"
str2 = "exam"
print(str1.find(str2, 7))
  • -1
  • 14
  • 0
  • 10

stay Python3 in strs.find(str, beg=0, end=len(strs)) It means that strs Back in First appearance str Location subscript of ,beg It means that strs Start index in , The default is 0( In this question 7),end End index , The default is strs The length of . But it should be noted that , The returned index is still from 0 At the beginning , Not at all beg Value (beg Just tell the program to start searching from the index of the string ), Therefore, the result of this question is 10

8. [str] The program that executes the following options , What throws an exception is ()

s1 = 'aabbcc'
s2 = 'abc'
count = s1.count(s2)
if count > 0 :
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
"""---------------------------"""
s1 = 'aabbcc'
s2 = 'abc'
index = s1.index(s2)
if index > -1:
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
"""---------------------------"""
s1 = 'aabbcc'
s2 = 'abc'
find = s1.find(s2)
if find != -1 :
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')
"""---------------------------"""
s1 = 'aabbcc'
s2 = 'abc'
if s2 in s1:
print('s2 yes s1 The string of ')
else:
print('s2 No s1 The string of ')

The correct answer is B.

  • count() The function does not match the object and returns 0
  • index() The function does not match the object and reports an error value Error
  • find() The function does not match the object and returns -1
  • in No match to the object returned False

9. [Python 2] what gets printed? Assuming python version 2.x()

print type(1/2)
  • <type ‘int’>
  • <type ‘number’>
  • <type ‘float’>
  • <type ‘double’>
  • <type ‘tuple’>
  • Python2 The middle division defaults to rounding down , therefore 1/2 = 0, Is an integer .
  • and Python3 The division in is the normal division , Will keep decimal places , therefore 1/2 = 0.5, It's floating point (float).

10. [class] There are the following class definitions , The following description is wrong ?

class A(object):
pass
class B(A):
pass
b = B()
  • isinstance(b, A) == True
  • isinstance(b, object) == True
  • issubclass(B, A) == True
  • issubclass(b, B) == True
  • isinstance() Function to determine whether an object is a known type , similar type().
  • issubclass() Function is used to determine whether the parameter is a subclass of the type parameter .

11. [ Sort ] On the list a = [1,2,3,1,2,4,6] After weight removal , Get the list b, Without considering the order of the list elements , The following method is wrong ()

b = list(set(a))
"""---------------------------"""
b = {
}
b = list(b.fromkeys(a))
"""---------------------------"""
a.sort()
b = []
i = 0
while i < len(a):
if a[i] not in b:
b.append(a[i])
else:
i += 1
"""---------------------------"""
a.sort()
for i in range(len(a)-1):
if a[i] == a[i+1]:
a.remove(a[i])
else:
continue
b = a

D The reason for the wrong option is for The number of cycles counted is constant , But as the a Repeated elements are constantly removed , Will cause the list to appear IndexError.

12. [ cycles ] stay Python3 in , The number of cycles of the following procedure is :

n = 1000
while n > 1:
print(n)
n = n / 2
  • 9
  • 10
  • 11
  • Infinite loop

This question means :n from 1000 Start the cycle , Each cycle executes n = n / 2, It is known that 29 = 512,210 = 1024, Therefore, the number of cycles is 10 Time , When the cycle 10 The cycle condition will not be satisfied after times

13. [set] stay Python3 in , The following statement is correct :

sets = {
1, 2, 3, 4, 5}
print(sets[2])

The result of program running is :

  • 2
  • 3
  • Report errors
  • {3}

python3 in , Collection cannot be indexed , So it will report a mistake :TypeError: ‘set’ object is not subscriptable
Set disorder , No index access

14. [ Variable scope ] Execute the following code , The output is ()

num = 1
def fn():
num += 1
return lambda:print(num)
x = fn()
x()
  • Report errors
  • 2
  • None
  • 1

Although it is declared outside the function num Is a global variable , But if the function body is right num Variable reassignment , As a result, the external global variables are shielded inside the function num, At this point, the statement num += 1 Will throw an exception , namely num Variables are directly referenced without first assigning values .

15. [ A shallow copy of a dictionary ] stay python3 in , The correct explanation of the program results is :

dicts = {
'one': 1, 'two': 2, 'three': 3}
tmp = dicts.copy()
tmp['one'] = 'abc'
print(dicts)
print(tmp)
  • [‘one’: 1, ‘two’: 2, ‘three’: 3],[‘one’: ‘abc’, ‘two’: 2, ‘three’: 3]
  • {‘one’: 1, ‘two’: 2, ‘three’: 3},{‘one’: ‘abc’, ‘two’: 2, ‘three’: 3}
  • {‘one’: ‘abc’, ‘two’: 2, ‘three’: 3},{‘one’: ‘abc’, ‘two’: 2, ‘three’: 3}
  • {‘one’: 1, ‘two’: 2, ‘three’: 3},{‘one’: 1, ‘two’: 2, ‘three’: 3}

Dictionary data type copy function , When simple values are replaced , The original dictionary and the copied dictionary do not affect each other , But when you add , Delete and other modification operations , The two will interact .
Therefore, the replacement of values in the new dictionary has no effect on the original dictionary

16. [str.find()] stay Python3 in , The result returned by the following procedure is :

strs = '123456'
print(strs.find('9'))
  • None
  • -1
  • Report errors
  • empty
  • find and rfind When you can't find it -1
  • index and rindex Return when you can't find it value error Therefore, it is recommended to use find

17. [ Coding sequence ] There is a passage python The coding procedure is as follows , What is the decoding order of the encoded string ( )

urllib.quote(line.decode("gbk").encode("utf-16"))
  • gbk utf16 url decode
  • gbk url decode utf16
  • url decode gbk utf16
  • url decode utf16 gbk

Pay attention to the examination , The question is that the decoding order is not the encoding order

18. [tuple assignment ] Perform the following procedure , The output is ()

def fun(a=(), b=[]):
a += (1, )
b.append(1)
return a, b
fun()
print(fun())
  • ((1,), [1, 1])
  • ((1,1), [1, 1])
  • ((1,), [1])
  • ((1,1), [1])

Python The default parameter of is assigned only once when the function is defined , Instead of creating a new reference every time the function is called . It means , When the function definition is complete , The default parameter already has a fixed memory address , If you use a variable default parameter and change it , Then later calls to this function will change this variable object , If the default parameter is an immutable object , There is no such problem , So the correct answer is A Options .
Pay attention to the examination , Two function calls

15. [filter & map] stay Python3 in , The result of the following program is :

strs = ['a', 'ab', 'abc', 'python']
y = filter(lambda s: len(s) > 2, strs)
tmp = list(map(lambda s: s.upper(), y))
print(tmp)
  • [‘ABC’, ‘PYTHON’]
  • [‘abc’, ‘PYTHON’]
  • [‘abc’, ‘python’]
  • [‘a’, ‘ab’]

filter The condition in this paper is pass Conditions
filter The output is a filter object , Can pass list, tuple Wait for the factory function to convert to the corresponding data type

16. [tuple How to define ] Which of the following is not Python How tuples are defined ?

  • (1)
  • (1, )
  • (1, 2)
  • (1, 2, (3, 4))

Python Medium tuple The structure is “ Immutable sequence ”, Use parentheses to indicate . To distinguish between parentheses that indicate priority in Mathematics , When tuple When there is only one element in , You need to add a comma after the element .

17. [dict Value ] stay python3 in , The result of the following procedure is :

dicts = {
'one': 1, 'two': 2, 'three': 3}
print(dicts['one'])
print(dicts['four'])
  • 1,[]
  • 1,{}
  • 1, Report errors
  • 1,None

py3 Access nonexistent indexes or key:

  • Dictionaries :
    • key Visiting newspaper KeyError
    • get Access the default return None
  • list 、 Tuples 、 character string :IndexError

py3 Slice out of bounds ( The index is a natural number ):

  • list :
    • start Transboundary : return [] An empty list
    • end Transboundary : Return to the shallow copy of the original list
    • start、end All out of bounds :[] An empty list
  • Tuples :
    • start Transboundary : return () An empty tuple
    • end Transboundary : Return the original tuple
    • start、end All out of bounds :() An empty tuple
  • character string :
    • start Transboundary : return ’’ Null character
    • end Transboundary : Returns the original string
    • start、end All out of bounds :'' Null character

18. [ comprehensive ] stay python3.x The program that executes the following options , What won't throw an exception is ()

b = 1
def fn():
nonlocal b
b = b + 1
print(b)
fn()
# ------------------------------------
tup = (('onion', 'apple'), ('tomato', 'pear'))
for _, fruit in tup:
print(fruit)
# ------------------------------------
a = [b for b in range(10) if b % 2 == 0]
print(b) # 
# ------------------------------------
lis = [1, 2, 'a', [1, 2]]
set(lis)
  • A Options , Variable b Belongs to global variable , So you should use global Declare not nonlocal;
  • B Options , have access to _ As placeholder , therefore B Options will not report errors ;
  • C Options ,python3.x in , Use list generation , Intermediate variable b Destroyed after generating the list , So use variables again b Will report a mistake ;
  • D Options , Collection elements cannot be non hashable objects such as lists , So it will report a mistake .

19. [return] The following about return It's true that ( )

  • python There must be return
  • return Multiple values can be returned
  • return When there is no return value , Function automatically returns Null
  • Execute to return when , The program will stop in the function return Subsequent statements
  • A. Function can have no return
  • B. look return Multiple values can be returned , But it's not , Multiple values are returned through tuple Realized
  • C. stay Python There is no Null This data type , The return should be None

20. [ Closed function ] Perform the following procedure , The output is ()

def fn():
t = []
i = 0
while i < 2:
t.append(lambda x: print(i * x, end=","))
i += 1
return t
for f in fn():
f(2)
  • 4,4,
  • 2,2,
  • 0,1,
  • 0,2,

function fn There is a closure phenomenon , The free variable is i, because python Closures adopt Delay binding , That is, when calling anonymous functions , The cycle is over , here i The value of is 2, So the output results are 2*2=4, The correct answer is A.

21. [is & ==] a And b The definition is as follows , Which of the following is true ?

a = '123'
b = '123'
  • a != b
  • a is b
  • a == 123
  • a + b = 246

a,b Is a string immutable type , So point to the same address , therefore a is b
+is Refers to the same address
== Same content
=== The content and format are the same
a+b=‘123123’
a==123, Characters and int inequality

22. [strip & rstrip] stay Python3 in , About strip() and rstrip() The program running result of is :

strs = ' I like python '
one = strs.strip()
print(one)
two = strs.rstrip()
print(two)
  • ‘I like python’, ‘I like python’
  • ’ I like python’, ’ I like python’
  • ‘I like python’, ’ I like python’
  • ‘I like python’, 'I like python ’
  • strip(): Delete leading and trailing spaces ;
  • rstrip(): Delete only the right space ;

23. [str.count] stay Python3 in , The running result of the character array is :

names = ["Andrea", "Aaslay", "Steven", "Joa"]
lists = []
for name in names:
if name.count('a') >= 2:
lists.append(name)
print(lists)
  • [‘Andrea’, ‘Aaslay’, ‘Joa’]
  • []
  • [‘Andrea’, ‘Aaslay’]
  • [‘Aaslay’]

This question means : Find the letters in the name from the character array of the name ‘a’ The number is greater than or equal to 2 A collection of name lists
First, traverse the character array of names to get each name , Re pass count() Function to determine whether the name contains letters ‘a’ The number is greater than or equal to 2 individual , Store the qualified name characters in lists Array ( We need to pay attention to ‘a’ It's case sensitive ), The last output lists = [‘Aaslay’]

24. [key] stay Python3 in , The correct statement about the running results of the program is :

dicts = {
}
dicts[([1, 2])] = 'abc'
print(dicts)
  • {([1,2]): ‘abc’}
  • {[1,2]: ‘abc’}
  • Report errors
  • None of the other statements are true

stay Python3 in , Only when all elements in a tuple are immutable , To become a dictionary key, Therefore, errors will be reported during the operation of the program :TypeError: unhashable type: ‘list’

25. [list.sort(key=, reverse=True)] Perform the following procedure , The output is ()

lis = ['apple', 'lemon', 'pear', 'peach']
def fn(x):
return x[::-1]
lis.sort(key=fn, reverse=True)
print(lis)
  • [‘apple’, ‘lemon’, ‘peach’,‘pear’]
  • [‘pear’, ‘peach’, ‘lemon’, ‘apple’]
  • [‘apple’,‘pear’, ‘lemon’, ‘peach’]
  • [‘pear’, ‘lemon’, ‘peach’, ‘apple’]

function fn The function of is to reverse the characters , such as fn("apple") obtain “elppa”. The elements in the list follow fn Function rules , Arrange in descending order , At this time, the list elements pass through the function rules :[‘elppa’,‘nomel’,‘raep’,hcaep], The descending order is as follows :[‘raep’, ‘nomel’, ‘hcaep’, ‘elppa’], But the list elements do not change , So the result is D.

26. [_,__,__*__] about Python Single underscore in class _foo、 Double underline __foo And __foo__ Members of , The following statement is correct ?

  • _foo Can't be used directly for from module import *
  • __foo The parser uses _classname__foo To replace the name , With the same name as other classes
  • __foo__ representative python A special way of marking
  • __foo Can be used directly from module import *

python There are four main ways of naming :

  1. object: Common method
  2. _object: Semi protected , Is seen as a “protect”, This means that only class objects and subclass objects can access these variables themselves , Cannot be used outside a module or class , Out-of-service from module import * Import .
    __object To avoid conflicts with subclass method names , The method described for this identifier , Methods of a parent class cannot be easily overridden by methods of a child class , Their names are actually _classname__methodname.
  3. __ object: All private , Full protection , Private member “private”, This means that only class objects can access , Even subclass objects can't access this data , Out-of-service from module import * Import .
  4. __ object__ : Built in method , Don't define it like this

27. [import The order ] When using import When importing a module , Press python The different order of finding modules can be divided into the following :

① In environment variable PYTHONPATH
② Built in module
③python The installation path
④ current path , The perform Python The path of the script file

The group with the correct search order is ()

  • ①④②③
  • ②①④③
  • ②④①③
  • ①②③④

python The order of searching modules is : Built in module > current path , The perform Python The path of the script file > In environment variable PYTHONPATH>python The installation path , Give a matrix C.
Built in module (built-in) > current path (./) > environment variable > Python The installation path

28. [id] The program that executes the following options , The output is True Yes. ()

lis = [1,3,2]
a = id(lis)
lis = sorted(lis)
b = id(lis)
print(a==b)
print("======================")
lis = [1,3,2]
a = id(lis)
lis += [4,5]
b = id(lis)
print(a==b)
print("======================")
tup = (1,3,2)
a = id(tup)
tup += (4,5)
b = id(tup)
print(a==b)
print("======================")
tup = (1,3,2)
a = id(tup)
tup = sorted(tup)
b = id(tup)
print(a==b)

Use sorted() Sorting will generate a new sequence , Generated new sequence and original sequence id The value must be different . For mutable objects ,sorted() When sorting, the original sequence also changes , And the subject A of use lis Saved the generated new sequence , therefore AD The output results of options are False; about += operation , If it's a mutable object , Then the sequence before and after the operation id The value remains the same , If it's an immutable object , Then the sequence before and after the operation id Value change , so B correct .

29. [split] stay Python3 in , The result of the following procedure is :

strs = ' I like python '
one = strs.split(' ')
two = strs.strip()
print(one)
print(two)
  • [‘’, ‘I’, ‘like’, ‘python’, ‘’],'I like python ’
  • [‘I’, ‘like’, ‘python’],‘I like python’
  • [‘’, ‘I’, ‘like’, ‘python’, ‘’],‘I like python’
  • [‘I’, ‘like’, ‘python’],'I like python ’

When there are spaces in the division , Then the space will be reserved when dividing .

30. [ comprehensive ] The program that executes the following options , What throws an exception is ()

a = 1
b = 2
a,b = b,a
print("================")
a,*b,c = range(5)
print(a,b,c)
print("================")
lis = ['1','2']
a,b = list(map(int,lis))
print(a,b)
print("================")
tup = (1,(2,3))
a,b,c = tup
print(a,b,c)

ABCD The program with four options is an iterative element unpacking problem .

  • A The option is an elegant way of exchanging two numbers ;
  • B Options ,python Allow to use * To handle the remaining parameters ;
  • C The option is about unpacking the list , Let the elements of the iteratable object be assigned to the corresponding variables one by one ;
  • D Option will throw an exception , This is because the corresponding variable does not satisfy the nested structure of tuples , The correct way of writing should be a,(b,c) = tup

31. [ illegal assignment ] Which of the following statements is in Python It's illegal ?

  • x = y = z = 1
  • x = (y = z + 1)
  • x, y = y, x
  • x += y

32. [str.endwith] The following code output is :

str = "Hello,Python";
suffix = "Python";
print (str.endswith(suffix,2));
  • True
  • False
  • Grammar mistakes
  • P

str.endswith(suffix[, start[, end]]) Used to determine whether the string ends with the specified suffix , If you return... At the end of the specified suffix True, Otherwise return to False.
Optional parameters "start" And "end" To retrieve the start and end of a string .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved