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

50 necessary Python interview questions (it is recommended to like them)

編輯:Python

In the past 2021 year ,Python Won the year TIOBE Programming language Award , Become The most popular programming language of the past year . In the fields of data science and machine learning , Widely used .

Prepare for war “ Kim San Yin four ”, Zi Ran sorted it out for everyone 50 Avenue Python Interview questions , There are corresponding answers , To help you better understand and learn Python.

▍1、 What is? Python? Why is it so popular ?

Python It's an explanation 、 advanced 、 Universal programming language .

Python The design idea is to use the necessary spaces and blank lines , Improve the readability of the code .

The reason it's popular , Because it has a simple and easy-to-use Syntax .

Interview question bank assistant can see this   It should be used in future interviews

 

 

▍2、 Why? Python Slow execution , How can we improve it ?

Python The reason for slow code execution , Because it is an interpretative language . Its code is interpreted at run time , Instead of compiling into a local language .

In order to improve the Python Code speed , We can use CPython、Numba, Or we can make some changes to the code .

1. Reduce memory usage .

2. Use built-in functions and Libraries .

3. Move the calculation out of the loop .

4. Keep a small code base .

5. Avoid unnecessary loops

▍3、Python What are the characteristics of ?

1. Easy to code

2. Free and open source languages

3. High-level language

4. Easy to debug

5. OOPS Support

6. A large number of standard libraries and third-party modules

7. Extensibility ( We can use C or C++ To write Python Code )

8. User friendly data structure

▍4、Python What are the applications ?

1. Web Development

2. desktop GUI Development

3. Artificial intelligence and machine learning

4. software development

5. Business application development

6. Console based applications

7. software test

8. Web automation

9. Audio or video based applications

10. Image processing applications

▍5、Python The limitations of ?

1. Speed

2. Mobile development

3. Memory consumption ( Very high compared with other languages )

4. The two versions are incompatible (2,3)

5. Running error ( Need more tests , And errors are only displayed at run time )

6. simplicity

▍6、Python How the code is executed ?

First , Interpreter reads Python Code and check for syntax or formatting errors .

If an error is found , Then suspend execution . If no errors are found , The interpreter will Python Convert code to equivalent form or byte code .

Then send the bytecode to Python virtual machine (PVM), here Python Code will be executed , If any mistakes are found , Then suspend execution , Otherwise, the results will be displayed in the output window .

▍7、 How to be in Python Manage memory in ?

Python Memory by Python Private ownership of headspace management .

be-all Python Objects and data structures are in a private heap . The private heap is allocated by Python The memory manager is responsible for .

Python There is also a built-in garbage collector , You can reclaim unused memory and free up memory , Make it available for headspace.

▍8、 explain Python Built in data structure ?

Python There are four main types of data structures in .

list : A list is a collection of heterogeneous data items from integers to strings or even another list . The list is variable . Lists do most of the work of aggregate data structures in other languages . List in [ ] Defined in square brackets .

for example :a = [1,2,3,4]

aggregate : A set is an unordered set of unique elements . Set operations such as union |, intersection & And the difference , Can be applied to collections . Set is immutable . Used to represent a collection .

for example :a = {1,2,3,4}

Tuples :Python Tuples work the same way Python The list is exactly the same , But they are immutable . Used to define tuples .

for example :a =(1,2,3,4)

Dictionaries : A dictionary is a collection of key value pairs . It is similar to... In other languages hash map. In the dictionary , Keys are unique and immutable objects .

for example :a = {‘number’:[1,2,3,4]}

▍9、 explain //、%、* * Operator ?

//(Floor Division)- This is a division operator , It returns the integer part of the division .

for example :5 // 2 = 2

%( modulus )- Returns the remainder of the Division .

for example :5 % 2 = 1

**( power )- It performs an exponential calculation on the operator .a ** b Express a Of b Power .

for example :5 ** 2 = 25、5 ** 3 = 125

▍10、Python What's the difference between single quotation marks and double quotation marks in ?

stay Python Use single quotes in (‘ ‘) Or double quotes (” “) There is no difference , Can be used to represent a string .

These two general expressions , In addition to simplifying programmer development , In addition to avoiding mistakes , There is another advantage , It can reduce the use of escape characters , Make the program look more concise , Clearer .

▍11、Python in append,insert and extend The difference between ?

append: Add new elements at the end of the list .

insert: Add an element at a specific location in the list .

extend: Expand the list by adding a new list .

numbers = [ 1, 2, 3, 4, 5]

numbers.append( 6)

print(numbers)

>[ 1, 2, 3, 4, 5, 6]

## insert(position,value)

numbers.insert( 2, 7)

print(numbers)

>[ 1, 2, 7, 4, 5, 6]

numbers.extend([ 7, 8, 9])

print(numbers)

>[ 1, 2, 7, 4, 5, 6, 7, 8, 9]

numbers.append([ 4, 5])

>[ 1, 2, 7, 4, 5, 6, 7, 8, 9,[ 4, 5]]

▍12、break、continue、pass What is it? ?

break: When we satisfy this condition , It will cause the program to exit the loop .

continue: Will return to the beginning of the loop , It causes the program to skip all remaining statements in the current loop iteration .

pass: Causes the program to pass all remaining statements without executing .

▍13、 distinguish Python Medium remove,del and pop?

remove: The first matching value in the list will be deleted , It takes values as parameters .

del: Use index to delete elements , It doesn't return any value .

pop: The top element in the list will be deleted , And return the top element of the list .

numbers = [ 1, 2, 3, 4, 5]

numbers.remove( 5)

> [ 1, 2, 3, 4]

delnumbers[ 0]

>[ 2, 3, 4]

numbers.pop

> 4

▍14、 What is? switch sentence . How to be in Python Created in switch sentence ?

switch Statement is to realize the function of multi branch selection , Test the variable according to the list value .

switch Each value in the statement is called a case.

stay Python in , No built-in switch function , But we can create a custom switch sentence .

switcher = {

1: “January”,

2: “February”,

3: “March”,

4: “April”,

5: “May”,

6: “June”,

7: “July”,

8: “August”,

9: “September”,

10: “October”,

11: “November”,

12: “December”

}

month = int(input)

print(switcher.get(month))

> 3

march

▍15、 Illustrate with examples Python Medium range function ?

range:range Function returns a series of sequences from start to end .

range(start, end, step), The third parameter is used to define the number of steps in the range .

# number

fori inrange( 5):

print(i)

> 0, 1, 2, 3, 4

# (start, end)

fori inrange( 1, 5):

print(i)

> 1, 2, 3, 4

# (start, end, step)

fori inrange( 0, 5, 2):

print(i)

> 0, 2, 4

▍16、== and is Is the difference between the ?

== Compare the equality of two objects or values .

is Operator is used to check whether two objects belong to the same memory object .

lst1 = [ 1, 2, 3]

lst2 = [ 1, 2, 3]

lst1 == lst2

> True

lst1 islst2

> False

▍17、 How to change the data type of the list ?

To change the data type of the list , have access to tuple perhaps set.

lst = [ 1, 2, 3, 4, 2]

# Change to set

set(lst) ## {1,2,3,4}

# Change to tuple

tuple(lst) ## (1,2,3,4,2)

▍18、Python How to annotate code in ?

stay Python in , We can comment in the following two ways .

1. Three quotes ”’, For multiline comments .

2. Single well number #, For single line comments .

▍19、!= and is not Operator differences ?

!= If the values of two variables or objects are not equal , Then return to true.

is not It is used to check whether two objects belong to the same memory object .

lst1 = [ 1, 2, 3, 4]

lst2 = [ 1, 2, 3, 4]

lst1 != lst2

> False

lst1 isnotlst2

> True

▍20、Python Is there a main function ?

Yes , It has . As long as we run Python Script , It will automatically execute .

▍21、 What is? lambda function ?

Lambda A function is a single line function without a name , Can have n Parameters , But there can only be one expression . Also known as anonymous functions .

a = lambdax, y:x + y

print(a( 5, 6))

> 11

▍22、iterables and iterators The difference between ?

iterable: Iteratable is an object , It can be iterated . In the case of iteration , The whole data is stored in memory at one time .

iterators: Iterators are objects used to iterate over objects . It is only initialized or stored in memory when called . Iterators use next Take the element out of the object .

# List is an iterable

lst = [ 1, 2, 3, 4, 5]

fori inlst:

print(i)

# iterator

lst1 = iter(lst)

next(lst1)

> 1

next(lst1)

> 2

fori inlst1:

print(i)

> 3, 4, 5

▍23、 Python Medium Map Function What is it? ?

map Function after applying a specific function to each item of the iteratable object , Returns the map object .

▍24、 explain Python Medium Filter?

Filter function , Filter values from iteratable objects based on certain criteria .

# iterable

lst = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

defeven(num):

ifnum% 2== 0:

returnnum

# filter all even numbers

list(filter(even,lst))

———————————————

[ 2, 4, 6, 8, 10]

▍25、 explain Python in reduce Function usage ?

reduce Function accepts a function and a sequence , And return the value after calculation .

fromfunctools importreduce

a = lambdax,y:x+y

print(reduce(a,[ 1, 2, 3, 4]))

> 10

▍26、 What is? pickling and unpickling?

pickling Yes, it will Python object ( Even Python Code ), The process of converting to a string .

unpickling Is the string , The inverse process of converting to the original object .

▍27、 explain *args and **kwargs?

*args, It is used when we are not sure about the number of arguments to be passed to the function .

def add(* num):

sum = 0

forval innum:

sum = val + sum

print(sum)

add( 4, 5)

add( 7, 4, 6)

add( 10, 34, 23)

———————

9

17

57

**kwargs, Is used when we want to pass a dictionary as an argument to a function .

▍28、 explain re Modular split、sub、subn Method ?

split: As long as the pattern matches , This method will split the string .

sub: This method is used to replace some patterns in a string with other strings or sequences .

subn: and sub Very similar , The difference is that it returns a tuple , Take the total replacement count and the new string as the output .

importre

string = “There are two ball in the basket 101”

re.split( “\W+”,string)

—————————————

[ ‘There’, ‘are’, ‘two’, ‘ball’, ‘in’, ‘the’, ‘basket’, ‘101’]

re.sub( “[^A-Za-z]”, ” “,string)

—————————————-

‘There are two ball in the basket’

re.subn( “[^A-Za-z]”, ” “,string)

—————————————–

( ‘There are two ball in the basket’, 10)

Interview question bank assistant can see this   It should be used in future interviews

 

 

▍29、Python What is the generator in ?

generator (generator) The definition of is similar to ordinary functions , The generator uses yield Keyword generated value .

If a function contains yield keyword , Then the function will automatically become a generator .

# A program to demonstrate the use of generator object with next A generator function

defFun:

yield1

yield2

yield3

# x is a generator object

x = Fun

print(next(x))

—————————–

1

print(next(x))

—————————–

2

▍30、 How to use index to reverse Python String in ?

string = ‘hello’

string[:: -1]

> ‘olleh’

▍31、 What's the difference between a class and an object ?

class (Class) A blueprint that is regarded as an object . The first line of string in the class is called doc character string , Contains a short description of the class .

stay Python in , Use class Keyword can create a class . A class contains a combination of variables and members , Called class members .

object (Object) Is a real entity . stay Python Create an object for the class in , We can use obj = CLASS_NAME

for example :obj = num

Objects using classes , We can access all members of the class , And operate on it .

classPerson:

“”” This is a Person Class”””

# varable

age = 10

defgreets(self):

print( ‘Hello’)

# object

obj = Person

print(obj.greet)

—————————————-

Hello

▍32、 You are right about Python Class self What do you know about ?

self Represents an instance of a class .

By using self keyword , We can do it in Python Access the properties and methods of the class in .

Be careful , In the functions of the class , You have to use self, Because there is no explicit syntax for declaring variables in the class .

▍33、_init_ stay Python What's the use of ?

“__init__” yes Python Class .

It's called a constructor , It is called automatically whenever the code is executed , It is mainly used to initialize all variables of the class .

▍34、 Explain it. Python Inheritance in ?

Inherit (inheritance) Allow one class to get all the members and properties of another class . Inheritance provides code reusability , It's easier to create and maintain applications .

The inherited class is called a superclass , An inherited class is called a derived class / Subclass .

▍35、Python in OOPS What is it? ?

object-oriented programming , abstract (Abstraction)、 encapsulation (Encapsulation)、 Inherit (Inheritance)、 polymorphic (Polymorphism)

▍36、 What is abstraction ?

abstract (Abstraction) It is to show the essence or necessary characteristics of an object to the outside world , And hide all other irrelevant information .

▍37、 What is encapsulation ?

encapsulation (Encapsulation) It means wrapping data and member functions together into a unit .

It also implements the concept of data hiding .

▍38、 What is polymorphism ?

polymorphic (Polymorphism) It means 「 Many forms 」.

Subclasses can define their own unique behavior , And still share its parent class / The same function or behavior of the base class .

▍39、 What is? Python Monkey patch in ?

Monkey patch (monkey patching), It refers to the dynamic modification of classes or modules at run time .

fromSomeOtherProduct.SomeModule importSomeClass

defspeak(self):

return”Hello!”

SomeClass.speak = speak

▍40、Python Support multiple inheritance ?

Python Can support multiple inheritance . Multiple inheritance means , A class can derive from more than one parent class .

▍41、Python Used in zip What is a function ?

zip Function gets an iterable object , Aggregate them into a tuple , And then return the result .

zip The syntax of the function is zip(*iterables)

numbers = [ 1, 2, 3]

string = [ ‘one’, ‘two’, ‘three’]

result = zip(numbers,string)

print(set(result))

————————————-

{( 3, ‘three’), ( 2, ‘two’), ( 1, ‘one’)}

▍42、 explain Python in map function ?

map Function applies a given function to an iteratable object ( list 、 Tuples etc. ), And then return the result (map object ).

We can still do that map Function , Pass multiple iteratable objects at the same time .

numbers = ( 1, 2, 3, 4)

result = map( lambdax: x + x, numbers)

print(list(result))

▍43、Python What is the decorator in ?

Decorator ( Decorator) yes Python An interesting feature in .

It is used to add functionality to existing code . This is also called metaprogramming , Because one part of the program will try to modify another part of the program at compile time .

defaddition(func):

definner(a,b):

print( “numbers are”,a, “and”,b)

returnfunc(a,b)

returninner

@addition

defadd(a,b):

print(a+b)

add( 5, 6)

———————————

numbers are 5and6

sum: 11

▍44、 Programming , Find the longest word in the text file

deflongest_word(filename):

withopen(filename, ‘r’) asinfile:

words = infile.read.split

max_len = len(max(words, key=len))

return[word forword inwords iflen(word) == max_len]

print(longest_word( ‘test.txt’))

—————————————————-

[ ‘comprehensions’]

▍45、 Programming , Check whether the sequence is palindrome

a = input( “Enter The sequence”)

ispalindrome = a == a[:: -1]

ispalindrome

> True

▍46、 Programming , Print the first ten items of the Fibonacci series

fibo = [ 0, 1]

[fibo.append(fibo[ -2]+fibo[ -1]) fori inrange( 8)]

fibo

> [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

▍47、 Programming , Calculate the frequency of words in the file

fromcollections importCounter

defword_count(fname):

withopen(fname) asf:

returnCounter(f.read.split)

print(word_count( “test.txt”))

▍48、 Programming , Output all prime numbers in a given sequence

lower = int(input( “Enter the lower range:”))

upper = int(input( “Enter the upper range:”))

list(filter( lambdax:all(x % y != 0fory inrange( 2, x)), range(lower, upper)))

————————————————-

Enter the lower range: 10

Enter the upper range: 50

[ 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

▍49、 Programming , Check if the number is Armstrong

Separate each number in turn , And add up its Cube ( digit ).

Last , If the sum is found to be equal to the original number , It is called Armstrong number (Armstrong).

num = int(input( “Enter the number:\n”))

order = len(str(num))

sum = 0

temp = num

whiletemp > 0:

digit = temp % 10

sum += digit ** order

temp //= 10

ifnum == sum:

print(num, “is an Armstrong number”)

else:

print(num, “is not an Armstrong number”)

▍50、 Use one line Python Code , Take all even and odd numbers from the given list

a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

odd, even = [el forel ina ifel % 2== 1], [el forel ina ifel % 2== 0]

print(odd,even)

> ([ 1, 3, 5, 7, 9], [ 2, 4, 6, 8, 10])

 

Interview question bank assistant can see this   It should be used in future interviews

 


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