IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Python Interview Question Summary -> 正文阅读

[Python知识库]Python Interview Question Summary

1, What is Python ? What are the benefits of using Python?

A1: high-level,interpreted, general-purpose programming language.

??? python supports objects,modules, threads, exception-handling,automatic memory management.

A2:

  • simple, easy to learn syntax, readability, reduce the cost of program maintenance
  • dynamic typing and dynamic binding

2. What is a dynamically typed language?

Static - Data Types are checked before execution.

Dynamic - Data Types are checked during execution

3. What is an interpreted language?

  • language executes its statements line by line
  • run directly from the source code.

4.What is PEP 8 and why is it important?

PEP---> Python Enhancement Proposal

PEP 8 is especially important since it documents the style guidelines for python code.

5.What is Scope in Python?

A scope is a block of code where an object in Python remain relevant.

  • A local scope refers to the local objects available in the current function.
  • A global scope refers to the objects available throught the code execution since their inception.
  • A module-level scope refers to the global objects of the current module accessible in the program.
  • An outermost-scope refers to all the built-in names callable in the program.

6, What are lists and tuples? What? is the key difference between the two?

  • Lists and tuples are both sequence data types that can store a collection of objects in python.
  • lists are represented with square brackets ['sara', 6, 0.19]
  • tuples are represented with parantheses ('ansh', 5, 0.97)

the key difference betwen the two?

  • lists are mutable, this means lists can be modified.append or sliced
  • tuples are immutable objects, this means tuples remain constant and cannot be modified in any manner.

7.What are the common built-in data types in Python?

  • Python provides type() and isinstance() functions to check the type of these variables.
  • None Type: None key represents the null values in Python.
  • Numeric Types: int ,float, complex, bool
  • Sequence Types :lists , tuples and range,str(text strings)
  • Mapping Types: dict(key-value)
  • Set Types: set(add(), remove()), fronzenset(immutable and can't be modified after creation)
  • Modules:
  • Callable Types:user-defined function,instance methods , generator functions,built-in functions, methods and classes.

8.What is pass in Python?

The pass keyword represents a null operation in Python.

def myEmptyFunc():
   # do nothing
   pass

myEmptyFunc()    # nothing happens

9.What are modules and packages in Python?

modules and packages allow for modular programming

Modularizing have several advantages:

  • Simplicity
  • Maintaninability
  • Reusability
  • Scoping

Modules: can be imported and initialized once using the import statement.
Packages:? allow using dot notation for module namespace.

Modules : help avoid clashes between global variable names.

Packages: help avoid clashes between module names.

10.What are global ,protected and private atttributes in Python?

  • Global : Public variables that are defined in the global scope. use the global keyword.
  • Protected : attributes defined with an underscore prefixed to their identifier. eg._sara.
  • Private: attributes with double underscore prefixed to their identifier. eg:__ansh.

11.What is the use of self in Python?

Self is used to represent the instance of the class. with this keyword, you can access the attributes and methods of the class in python.? self is not a keyword in Python.

12.What is __init__?

  • __init__ is a contructor method in Python
  • is automatically called to allocate memory when a new object /instance is created.
# class definition
class Student:
   def __init__(self, fname, lname, age, section):
       self.firstname = fname
       self.lastname = lname
       self.age = age
       self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")

13.What is break, continue? and pass in Python?

  • Break : Terminates the loop immediately and the control flows to the statement after the body of the loop.
  • Continue: Terminate the current iteration of the statement
  • Pass : fill up empty blocks
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
   pass
   if (p == 0):
       current = p
       break
   elif (p % 2 == 0):
       continue
   print(p)    # output => 1 3 1 3 1
print(current)    # output => 0

14.What are unit tests in Python?

  • Unit test is a unit testing framework of Python.
  • Unit testing means testing different components of software separately.

15. What is docstring in Python?

  • Documentation string or docstring is a multiline string used to document a specific code segment.
  • The docstring should describe what the function or method does.

16.What is slicing in Python?

  • 'slicing' is taking parts of
  • Syntax for slicing is [start:stop:step]
  • start is the starting index from where to slice a list or tuple
  • stop is the ending index or where to sop.
  • step is the number of steps to jump.
  • Default value for start is 0, stop is number of items, step is 1
  • Slicing can be done on strings, arrays, lists? and tuples.

17. Expalin how you can make a Python script executable on Unix?

Script file must begin with #!/usr/bin/env python

# pound 井号

/ slash, divide, oblique 斜线,斜杠,除号

! exclamation mark (英式英语)

18.What is the difference between Python Arrays and lists?

  • Arrays : Only contain emlements of same data types. data type of array should be homogeneous (同质的,同类的) comsume far less memory than lists.
  • Lists can contain elements of different data types. data type of lists can be heterogeneous(各种各样的).? consuming large memory.
import array
a = array.array('i', [1, 2, 3])
for i in a:
    print(i, end=' ')    #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string'])    #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
   print(i, end=' ')    #OUTPUT: 1 2 string

19. How is memory managed in Python?

  • Python Memory Manager(private heap space)
  • Python has an in-built garbage collection to recycle the unused memory for the private heap space.

20.What are Python namespaces? Why are they used?

A namespace ensures that object names in a program are unique and can be used without conflict.

  • Local Namespace : local names inside a function.
  • Global Namespace includes name from various imported /modules that are being used in the current project.
  • Built-in Namespace includes built-in functions of core Python and built-in names for various types of executions.

21: What are decorators in Python?

Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself.

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]

23. What are Dict and List comprehensions?

Performing mathemaical operations on the entire list

my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list]    # list comprehension
# output => [4 , 9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list}    # dict comprehension
# output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}

Performing conditional filtering operations on the entire list.

my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension
# output => {11: 121, 3: 9 , 5: 25 , 7: 49}

Combining multiple lists into one

a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)]  # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b]    # nested iterators
# output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)] 

Flattening a multi-dimensional list

my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10, 20, 30, 40, 50, 60, 70, 80, 90]

24.What is lambda in Python? Why is it used?

Lambda is an anomymous function in Python, That can accept any number of arguments, but can only have a single expression.

Assigning lambda function to a variable:

mul = lambda a, b : a * b
print(mul(2, 5))    # output => 10

Wrapping lambda functions inside another function:

def myWrapper(n):
 return lambda a : a * n
mulFive = myWrapper(5)
print(mulFive(2))    # output => 10

25.How do you copy an object in Python?

use the copy module.

Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object.

Deep Copy copies all values recursively from source to target object.

from copy import copy, deepcopy
list_1 = [1, 2, [3, 5], 4]
## shallow copy
list_2 = copy(list_1) 
list_2[3] = 7
list_2[2].append(6)
list_2    # output => [1, 2, [3, 5, 6], 7]
list_1    # output => [1, 2, [3, 5, 6], 4]
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
list_3    # output => [1, 2, [3, 5, 6, 7], 8]
list_1    # output => [1, 2, [3, 5, 6], 4]

26. What is the difference between xrange and range in Python?

  • xrange() and range() are quite similar in terms of functionality.
  • range() return a Python list. xrange() returns an xrange object.
for i in xrange(10):    # numbers from o to 9
   print i       # output => 0 1 2 3 4 5 6 7 8 9
for i in xrange(1,10):    # numbers from 1 to 9
   print i       # output => 1 2 3 4 5 6 7 8 9
for i in xrange(1, 10, 2):    # skip by two for next
   print i       # output => 1 3 5 7 9

27. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

28. What is the use of help() and dir() functions?

help()?function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the?help()?function, then an interactive?help utility?is launched on the console.
dir()?function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information.

29.What is the difference between .py and .pyc files?

.py files contain the source code of a program.

.pyc file contain the bytecode of your program.

Having .pyc file saves you the compilation time.

30. How Python is interpreted?

Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation . Python is a bytecode interpreted generally.

Source code is a file with .py extension.

Python compiles the source code to a set of instructions for a virtual machine.

.py source code is first compiled to give .pyc which is bytecode.

31. How are arguments passed by value or by reference in python?

  • Pass by value : Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference : Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.
def appendNumber(arr):
   arr.append(4)
arr = [1, 2, 3]
print(arr)  #Output: => [1, 2, 3]
appendNumber(arr)
print(arr)  #Output: => [1, 2, 3, 4]

32. What are iterators in Python?

  • An iterator is an object.
  • It remembers its state
  • __iter__() method initializes an iterator
  • __next__() method which returns the next item in iteration and points to the next element.

33.Explain how to delete a file in Python?

Use command os.remove(file_name)

import os
os.remove("ChangedFile.csv")
print("File Removed!")

34.Explain split() and join() functions in Python?

use split() function to split a string based on a delimiter to a list of strings.

use join() function to join a list of strings based on a delimiter to give a single string.

string = "This is a string."
string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘
print(string_list) #output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list)) #output: This is a string.

35.What does *args and **kwargs mean?

*args

  • *args is a special syntax used in the function definition to pass variable-length arguments.
  • “*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):
   mul = a * b
   for num in argv:
       mul *= num
   return mul
print(multiply(1, 2, 3, 4, 5)) #output: 120

**kwargs

  • **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable that has a name when passed to a function.
  • It is actually a dictionary of the variable names and its value.
def tellArguments(**kwargs):
   for key, value in kwargs.items():
       print(key + ": " + value)
tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3")
#output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

36. What are negative indexes and why are they used ?

  • Negative indexes are the indexes from the end of the list or tuple or string.
  • Arr[-1]?means the last element of array?Arr[]
arr = [1, 2, 3, 4, 5, 6]
#get the last element
print(arr[-1]) #output 6
#get the second last element
print(arr[-2]) #output 5

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2022-09-21 00:24:34  更:2022-09-21 00:25:37 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 10:07:22-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码