Home > Backend Development > Python Tutorial > Gold three, silver four, 50 essential Python interview questions (recommended collection)

Gold three, silver four, 50 essential Python interview questions (recommended collection)

Release: 2023-08-15 14:41:13
forward
1224 people have browsed it


## In the past 2020, Python won the TIOBE Programming Language of the Year Award and became the past The most popular programming language of the year. It is widely used in fields such as data science and machine learning.


## It’s the recruitment season of “Gold, Three, Silver and Four”. Little F gives We have compiled 50 Python interview questions and corresponding answers to help you better understand and learn Python.



##▍1. What is Python? Why is it so popular?

Python is an interpreted, high-level, general-purpose programming language.


The design philosophy of Python is to enhance the readability of the code by using necessary spaces and blank lines.


It is popular because of its simple and easy-to-use syntax.


#▍2. Why Python Execution is slow, how can we improve it?


The reason why Python code executes slowly is because it is an interpreted language. Its code is interpreted at runtime rather than compiled into the native language.


In order to improve the speed of Python code, we can use CPython, Numba, or we can also make some modifications to the code .


1. Reduce memory usage.

2. Use built-in functions and libraries.

3. Move the calculation outside the loop.

4. Keep the code base small.

5. Avoid unnecessary loops



▍3. What are the characteristics of Python?


1. Easy to code

2 . Free and open source languages

3. High-level languages

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 CWrite Pythoncode)

8. User-friendly data structures



##▍4.What are the applications of Python?


1. Web Development

2 . Desktop GUI Development

3. Artificial Intelligence and Machine Learning

4. Software Development

5. Business Application Development

6. Console-based application

7. Software testing

8. Web automation

9. Audio or video based applications

10. Image processing applications



▍5. What are the limitations of Python?

1. Speed

2. Mobile development

3. Memory consumption (very high compared to other languages)

4. Two Incompatible version (2, 3)

5. Run error (more testing is needed, and the error is only displayed at run time)

6. Simplicity



##▍6, How is Python code executed?


First, the interpreter reads the Python code and checks for syntax or formatting errors.


If an error is found, execution is paused. If no errors are found, the interpreter converts the Python code into its equivalent form, or byte code.


The bytecode is then sent to the Python Virtual Machine (PVM), where the Python code will be executed if found On any errors, execution is paused, otherwise the results are displayed in the output window.


Gold three, silver four, 50 essential Python interview questions (recommended collection)



#▍7. How to manage memory in Python?


Python memory is managed by Python’s private headspace.


All Python objects and data structures are located in a private heap. Private heap allocation is the responsibility of the Python memory manager.


Python also has a built-in garbage collector that can recycle unused memory and release the memory to make it available. in headspace.



## 8. Explain Python’s built-in data structures?

There are four main types of data structures in Python.


List: A list is a collection of heterogeneous data items ranging from integers to strings or even another list. Lists are mutable. Lists do the job of most collection data structures in other languages. Lists are defined within [ ] square brackets.

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


##Set: A set is an unordered collection of unique elements. Set operations such as union|, intersection& and difference can be applied to sets. Sets are immutable. () is used to represent a set.

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


##Tuples: Python tuples work exactly like Python lists, except that they are immutable. () is used to define tuples.

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


Dictionary: A dictionary is a collection of key-value pairs. It is similar to hash maps in other languages. In a dictionary, keys are unique and immutable objects.

For example: a = {'number':[1,2,3,4]}



##▍9. Explanation of //, %, * *operators?


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

For example: 5 // 2 = 2


##% (modulo) - returns the result of division remainder.

For example: 5 % 2 = 1


##**(Power ) - It performs exponential calculations on the operator. a ** b represents a raised to the bth power.

For example: 5 ** 2 = 25, 5 ** 3 = 125


##

▍10. What is the difference between single quotes and double quotes in P?


##Use single quotes (' ') or double quotes ( " ") has no difference, both can be used to represent a string.


In addition to simplifying the development of programmers and avoiding errors, these two general expressions also have a One benefit is that it can reduce the use of escape characters and make the program look simpler and clearer.



▍11. What are the differences between append, insert and extend in Python?


append: Adds a new element to the end of the list.

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

extend: Extend a 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]]
Copy after login


##

▍12. What are break, continue and pass?


break: It will cause the program to exit the loop when the condition is met.

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

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


▍13、区分Python中的remove,del和pop?


remove:将删除列表中的第一个匹配值,它以值作为参数。

del:使用索引删除元素,它不返回任何值。

pop:将删除列表中顶部的元素,并返回列表的顶部元素。


numbers = [1,2,3,4,5]
numbers.remove(5)
> [1,2,3,4]

del numbers[0]
>[2,3,4]

numbers.pop()
>4
Copy after login



▍14、什么是switch语句。如何在Python中创建switch语句?


switch语句是实现多分支选择功能,根据列表值测试变量。

switch语句中的每个值都被称为一个case。

在Python中,没有内置switch函数,但是我们可以创建一个自定义的switch语句。

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
Copy after login


▍15、举例说明Python中的range函数?


range:range函数返回从起点到终点的一系列序列。

range(start, end, step),第三个参数是用于定义范围内的步数。


# number
for i in range(5):
    print(i)
> 0,1,2,3,4

# (start, end)
for i in range(1, 5):
    print(i)
> 1,2,3,4

# (start, end, step)
for i in range(0, 5, 2):
    print(i)
>0,2,4
Copy after login



▍16、==和is的区别是?


==比较两个对象或值的相等性

is运算符用于检查两个对象是否属于同一内存对象。


lst1 = [1,2,3]
lst2 = [1,2,3]

lst1 == lst2
>True

lst1 is lst2
>False
Copy after login


▍17、如何更改列表的数据类型?


要将列表的数据类型进行更改,可以使用tuple()或者set()。


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

# 更改为集合
set(lst)    ## {1,2,3,4}
# 更改为元组
tuple(lst)  ## (1,2,3,4,2)
Copy after login



▍18、Python中注释代码的方法有哪些?


在Python中,我们可以通过下面两种方式进行注释。


1. 三引号''',用于多行注释。

2. 单井号#,用于单行注释。



▍19、!=和is not运算符的区别?


!=如果两个变量或对象的值不相等,则返回true。

is not是用来检查两个对象是否属于同一内存对象。


lst1 = [1,2,3,4]
lst2 = [1,2,3,4]

lst1 != lst2
>False

lst1 is not lst2
>True
Copy after login



▍20. Does Python have a main function?


Yes, it does. As soon as we run the Python script, it will execute automatically.



#▍21、What is lambda function?


Lambda function is a single-line function without a name and can have n parameters, but There can only be one expression. Also called anonymous functions.


a = lambda x, y:x + y 
print(a(5, 6))

> 11
Copy after login



▍22、iterables和iterators之间的区别?


iterable:可迭代是一个对象,可以对其进行迭代。在可迭代的情况下,整个数据一次存储在内存中。


iterators:迭代器是用来在对象上迭代的对象。它只在被调用时被初始化或存储在内存中。迭代器使用next从对象中取出元素。


# List is an iterable
lst = [1,2,3,4,5]
for i in lst:
    print(i)

# iterator
lst1 = iter(lst)
next(lst1)
>1
next(lst1)
>2
for i in lst1:
    print(i)
>3,4,5
Copy after login



▍23、Python中的Map Function是什么?


map函数在对可迭代对象的每一项应用特定函数后,会返回map对象。



▍24、解释Python中的Filter


过滤器函数,根据某些条件从可迭代对象中筛选值。


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

def even(num):
    if num%2==0:
        return num

# filter all even numbers
list(filter(even,lst))
---------------------------------------------
[2, 4, 6, 8, 10]
Copy after login



▍25、解释Python中reduce函数的用法?


reduce()函数接受一个函数和一个序列,并在计算后返回数值。


from functools import reduce

a = lambda x,y:x+y
print(reduce(a,[1,2,3,4]))

> 10
Copy after login



▍26. What are pickling and unpickling?


pickling is the process of converting Python objects (or even Python code) into strings.

Unpickling is the reverse process of converting a string into the original object.



##▍27, Explain *args and **kwargs?


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


def add(* num):
    sum = 0 
    for val in num:
        sum = val + sum 
    print(sum)


add(4,5)
add(7,4,6)
add(10,34,23)
--------------------- 
9 
17 
57
Copy after login


**kwargs,是当我们想将字典作为参数传递给函数时使用的。


def intro(**data):
    print("\nData type of argument:",type(data))
    for key, value in data.items():
        print("{} is {}".format(key,value))


intro(name="alex",Age=22, Phone=1234567890)
intro(name="louis",Email="a@gmail.com",Country="Wakanda", Age=25)
--------------------------------------------------------------
Data type of argument: <class &#39;dict&#39;>
name is alex
Age is 22
Phone is 1234567890

Data type of argument: <class &#39;dict&#39;>
name is louis
Email is a@gmail.com
Country is Wakanda
Age is 25
Copy after login



▍28、解释re模块的split()、sub()、subn()方法


split():只要模式匹配,此方法就会拆分字符串。

sub():此方法用于将字符串中的某些模式替换为其他字符串或序列。

subn():和sub()很相似,不同之处在于它返回一个元组,将总替换计数和新字符串作为输出。


import re
string = "There are two ball in the basket 101"


re.split("\W+",string)
---------------------------------------
[&#39;There&#39;, &#39;are&#39;, &#39;two&#39;, &#39;ball&#39;, &#39;in&#39;, &#39;the&#39;, &#39;basket&#39;, &#39;101&#39;]

re.sub("[^A-Za-z]"," ",string)
----------------------------------------
&#39;There are two ball in the basket&#39;

re.subn("[^A-Za-z]"," ",string)
-----------------------------------------
(&#39;There are two ball in the basket&#39;, 10)
Copy after login



▍29、Python中的生成器是什么


生成器(generator)的定义与普通函数类似,生成器使用yield关键字生成值。


如果一个函数包含yield关键字,那么该函数将自动成为一个生成器。


# A program to demonstrate the use of generator object with next() A generator function 
def Fun(): 
   yield 1
   yield 2
   yield 3

# x is a generator object 
x = Fun()
print(next(x))
-----------------------------
1
print(next(x))
-----------------------------
2
Copy after login



▍30、如何使用索引来反转Python中的字符串?


string = &#39;hello&#39;

string[::-1]
>&#39;olleh&#39;
Copy after login



▍31、类和对象有什么区别?


类(Class)被视为对象的蓝图。类中的第一行字符串称为doc字符串,包含该类的简短描述。


在Python中,使用class关键字可以创建了一个类。一个类包含变量和成员组合,称为类成员。


对象(Object)是真实存在的实体。在Python中为类创建一个对象,我们可以使用obj = CLASS_NAME()

例如:obj = num()


使用类的对象,我们可以访问类的所有成员,并对其进行操作。


class Person:
    """ This is a Person Class"""
    # varable
    age = 10
    def greets(self):
        print(&#39;Hello&#39;)


# object
obj = Person()
print(obj.greet)
----------------------------------------
Hello
Copy after login



▍32、你对Python类中的self有什么了解?


self represents an instance of a class.


By using the self keyword, we can access the properties and methods of a class in Python.


Note that self must be used in class functions because there is no explicit method for declaring variables in the class grammar.



▍33. What is the use of _init_ in Python?


"__init__" is a reserved method in Python classes.


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



▍34. Explain inheritance in Python?


Inheritance allows one class to obtain all members and properties of another class. InheritanceInheritance provides code reusability, making it easier to create and maintain applications.


The class that is inherited is called a super class, and the class that is inherited is called a derived class/subclass.



▍35. What is OOPS in Python?


##Object-oriented programming, abstraction, Encapsulation, Inheritance, Polymorphism



##▍ 36. What is abstraction?


##Abstraction is the transfer of the essence or necessary characteristics of an object to The process of displaying it to the outside world and hiding all other irrelevant information.



##▍37. What is encapsulation?


Encapsulation means packaging data and member functions together into a unit.


It also implements the concept of data hiding.



##▍38. What is polymorphism?


Polymorphism means "many forms."


Subclasses can define their own unique behavior and still share the same functionality or behavior of their parent/base class .



##▍39. What is monkey patching in Python?


Monkey patching refers to dynamically modifying classes or modules at runtime.


from SomeOtherProduct.SomeModule import SomeClass

def speak(self):
    return "Hello!"

SomeClass.speak = speak
Copy after login



▍40、Python支持多重继承吗?


Python可以支持多重继承。多重继承意味着,一个类可以从多个父类派生。



▍41、Python中使用的zip函数是什么?


zip函数获取可迭代对象,将它们聚合到一个元组中,然后返回结果。


zip()函数的语法是zip(*iterables)


numbers = [1, 2, 3]
string = [&#39;one&#39;, &#39;two&#39;, &#39;three&#39;] 
result = zip(numbers,string)

print(set(result))
-------------------------------------
{(3, &#39;three&#39;), (2, &#39;two&#39;), (1, &#39;one&#39;)}
Copy after login



▍42、解释Python中map()函数?


map()函数将给定函数应用于可迭代对象(列表、元组等),然后返回结果(map对象)。


我们还可以在map()函数中,同时传递多个可迭代对象。


numbers = (1, 2, 3, 4)
result = map(lambda x: x + x, numbers)

print(list(result))
Copy after login



▍43、Python中的装饰器是什么?


装饰器(Decorator)是Python中一个有趣的功能。


它用于向现有代码添加功能。这也称为元编程,因为程序的一部分在编译时会尝试修改程序的另一部分。


def addition(func):
    def inner(a,b):
        print("numbers are",a,"and",b)
        return func(a,b)
    return inner

@addition
def add(a,b):
   print(a+b)

add(5,6)
---------------------------------
numbers are 5 and 6
sum: 11
Copy after login



▍44、编写程序,查找文本文件中最长的单词


def longest_word(filename):
    with open(filename, &#39;r&#39;) as infile:
              words = infile.read().split()
    max_len = len(max(words, key=len))
    return [word for word in words if len(word) == max_len]

print(longest_word(&#39;test.txt&#39;))
----------------------------------------------------
[&#39;comprehensions&#39;]
Copy after login



▍45、编写程序,检查序列是否为回文


a = input("Enter The sequence")
ispalindrome = a == a[::-1]

ispalindrome
>True
Copy after login



▍46、编写程序,打印斐波那契数列的前十项


fibo = [0,1]
[fibo.append(fibo[-2]+fibo[-1]) for i in range(8)]

fibo
> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Copy after login



▍47、编写程序,计算文件中单词的出现频率


from collections import Counter

def word_count(fname):
        with open(fname) as f:
                return Counter(f.read().split())

print(word_count("test.txt"))
Copy after login



▍48、编写程序,输出给定序列中的所有质数


lower = int(input("Enter the lower range:"))
upper = int(input("Enter the upper range:"))
list(filter(lambda x:all(x % y != 0 for y in range(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]
Copy after login


▍49、编写程序,检查数字是否为Armstrong


Gold three, silver four, 50 essential Python interview questions (recommended collection)


将每个数字依次分离,并累加其立方(位数)。


最后,如果发现总和等于原始数,则称为阿姆斯特朗数(Armstrong)。


num = int(input("Enter the number:\n"))
order = len(str(num))

sum = 0
temp = num

while temp > 0:
   digit = temp % 10
   sum += digit ** order
   temp //= 10

if num == sum:
   print(num,"is an Armstrong number")
else:
   print(num,"is not an Armstrong number")
Copy after login



▍50、用一行Python代码,从给定列表中取出所有的偶数和奇数


a = [1,2,3,4,5,6,7,8,9,10]
odd, even = [el for el in a if el % 2==1], [el for el in a if el % 2==0]

print(odd,even)
> ([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
Copy after login


The above is the detailed content of Gold three, silver four, 50 essential Python interview questions (recommended collection). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Python当打之年
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template