The Python face questions you answer again?

Basics

1. List five commonly used Python standard library?

import os
import sys
import re
import math
import time
import datetime
import random
import threading
import multiprocessing

2. Python's built-in data types are there?

int、float、complex         # 数值型
bool            # 布尔型
str             # 字符串
list            # 列表
tuple           # 元组
dict            # 字典

3. The method briefly with open file handle to help us to do what?

statement for the occasion with access to resources, ensuring that regardless of whether an exception occurs during use to perform the necessary cleanup operations, the release of resources, such as files automatically shut down after, thread lock automatically acquire and release;

i.e., context manager with statement in the program code to represent the execution environment in which the front and rear. Context Manager: containing enter and exit object methods is context manager.

enter (): prior to performing with the statement, the first implementation of the method usually returns an instance of the object, as if there is a target with the statement, the object is assigned to as a target. exit (): After the execution with the statement, automatically call the Exit () method, the user releases the resource, if this method returns a Boolean value True, the program will ignore the exception. Environment: file read and write, thread lock automatically released and so on.

with context_expression [as target(s)]:
    with-body
        ```
这里context_expression要返回一个上下文管理器对象,该对象并不赋值给as子句中的target(s),而是会将上下文管理器的__enter__()方法的返回值赋值给target(s)。

**4. Python的可变和不可变数据类型?**

不可变数据类型:即数据被创建之后,数据的值将不再发生改变,有数值、字符、元祖类型;
可变数据类型:数据别创建之后,数据的值可以发生变化,有列表、字典、集合类型。

**5. Python获取当前日期?**

-- coding: UTF-8 --

datetime Time IF Import Import name == " main ": Print (the time.time ()) # stamp print (time.strftime ( "% Y-% m-% d% H:% M:% S% w" , time.localtime ())) # year, month, day, hour print (datetime.datetime.now ()) # year, month, day, hour `` `

6. Statistical number string for each word appears.

def word_amount(sentence):
    split_list = sentence.split()
    dict_result = {}
    for word_name in split_list:
        if word_name not in dict_result.keys():
            dict_result[word_name] = 1
        else:
            dict_result[word_name] += 1
    return dict_result
​
if __name__ == '__main__':
    sentence = "I can because i think i can"
    dict_result = word_amount(sentence)
    print(dict_result)
        ```
或者:

if name == 'main': sentence = "I can because i think i can" result = {word: sentence.split().count(word) for word in set(sentence.split())} print(result) ``` 或者:

from collections import Counter
​
if __name__ == '__main__':
    sentence = "I can because i think i can"
    counts = Counter(sentence.split())
    print(counts)
        ```
7.用python删除文件和用linux命令删除文件方法。

import os os.remove("demo.txt") rm demo.txt


8.写一段自定义异常代码?

printException class (Exception): Pass DEF testRaise (): The raise printException ( 'printErr') IF name == ' main ': the try: testRaise () the except printException, E: Print E `` `module 9. The illustrated abnormal the try except else finally the relevance.

# -*- coding: UTF-8 -*-
​
def read_filedata(file_name):
    file_obj = ""
    try:
        # 需要检测的异常代码片段
        file_obj = open(file_name, "r")
        result_data = file_obj.read()
    except IOError, e:
        # 发生“IOError”异常进行处理的代码片段
        file_obj = "文件不存在:"+ str(e)
    else:
        # 没有引发“IOError”异常执行的代码片段,返回读取到的数据
        return result_data
    finally:
        # 不管有没有引发错误都会执行的代码片段,isinstance()用于判断一个数据类型
        if isinstance(file_obj, str):
            return file_obj
        elif isinstance(file_obj, file):
            file_obj.close()
        else:
            return "未知错误,请检查您的代码..."
​
if __name__ == '__main__':
    result = read_filedata("abc.txt")
    print(result)
        ```

10.遇到 bug 如何处理?

首先查看报错信息,根据报错信息找到相应代码,通常一般的数据结构或者算法错误只要找到报错代码就可以顺利解决;

如果遇到暂时不能解决的错误先不要慌,我们可以使用编译器的Debug模式或者自己在代码中加注断点进行代码排查;

如果依然不能解决bug,我们可以拷贝报错信息,在搜索引擎中进行搜索。没有人写代码不出bug,如果你在一个bug上耗费时间超过半小时,可以与其他同事探讨(注意节制,可能有些费同事);

另辟蹊径:方法总比困难多,在进行快速开发时,我们应该优先实现功能而不是拘泥于运行效率,所以遇到一些暂时不能解决的BUG可以考虑另外的实现方法。

#### 语言特性

**1.谈谈对Python的了解和其他语言的区别?**

Python是一门语法简洁优美,功能强大无比,应用领域非常广泛,具有强大完备的第三方库的一门强类型的动态,可移植,可扩展,可嵌入的解释型编程语言。

**强类型语言、弱类型语言的区别:**

如果语言经常隐式地转换变量的类型,那这个语言就是弱类型语言,如果很少会这样做,那就是强类型语言。Python很少会隐式地转换变量的类型,所以Python是强类型的语言。

强类型语言和弱类型原因其判断的根本是是否会隐式进行语言类型转变。强类型原因在速度上可能略逊于弱类型语言,但是强类型定义语带来的严谨性又避免了不必要的错误。

强类型语言包括:Java、.net、Python、C++等语言。其中Python是动态语言,是强类型定义语言,是类型安全的语言,Java是静态语言,是强类型定义语言,也是类型安全的语言;弱类型语言包括:VB,PHP,JavaScript等语言。其中VBScript是动态语言,是一种类型不安全的原因。

**动态语言、静态语言的区别:**

动态类型语言:动态性语言是指在运行期间才去做数据类型检查的语言,也就是说动态类型语言编程时,永远不用给任何变量指定数据类型,该语言会在第一次赋值给变量时,在内部将数据类型记录下来。Python和Ruby就是一种典型的动态类型语言,其他的各种脚本语言如VBScript也多少属于动态类型语言。

静态类型语言:静态类型语言与动态类则刚好相反,它的数据类型在编译期间检查,也就是说在写程序时要声明所有变量的数据类型,C/C++是静态类型语言的典型代表,其他静态语言还有C#、Java等。

对于动态语言与静态语言的区分,其根本在于数据类型是在运行期间检查还是在编译期间检查。

**编译型语言、解释型语言的区别:**

编译型语言:需要将一段程序直接翻译成机器码(对于C/C++这种非跨平台的语言)或者中间码(Java这种跨平台语言,需要虚拟机再将中间码印射成机器码)。一般需经过编译(compile)、链接(linker)这两个步骤。编译是把源代码编译成机器码,链接是把各个模块的机器码和依赖库串连起来生成可执行文件。

解释型语言:使用解释器将源码逐行解释成机器码并立即执行,不会进行整体性的编译和链接处理,相比编译型语言省了道工序。
一个像是吃饭等菜都上全了再开动,一个像是吃火锅,边涮边吃,时机不一样。

解释型语言的优点:跨平台容易,只需提供特定平台的解释器;缺点:每次运行的时候都要解释一遍,性能上不如编译型语言。

**2.Python的解释器种类以及相关特点?**

CPython:官方版本的解释器。这个解释器是用C语言开发的,所以叫CPython。在命令行下运行python就是启动CPython解释器。CPython是使用最广的Python解释器。

IPython:IPython是基于CPython之上的一个交互式解释器,也就是说,IPython只是在交互方式上有所增强,但是执行Python代码的功能和CPython是完全一样的。CPython用>>>作为提示符,而IPython用In [序号]:作为提示符。

PyPy:它的目标是执行速度。PyPy采用JIT技术,对Python代码进行动态编译(注意不是解释),所以可以显著提高Python代码的执行速度。绝大部分Python代码都可以在PyPy下运行,但是PyPy和CPython有一些是不同的,这就导致相同的Python代码在两种解释器下执行可能会有不同的结果。

Jython:Jython是运行在Java平台上的Python解释器,可以直接把Python代码编译成Java字节码执行。

**3、说说你知道的Python3和Python2之间的区别?**

编码:Python2的默认编码是asscii,这也是导致Python2中经常遇到编码问题的原因之一,至于是为什么会使用asscii作为默认编码,原因在于Python这门语言诞生的时候还没出现Unicode。Python3默认采用了UTF-8作为默认编码,因此你不再需要在文件顶部写# coding=utf-8了。

字符串:Python2中字符的类型,str:已经编码后的字节序列,unicode:编码前的文本字符;而Python3中字符的类型,str:编码过的unicode文本字符,bytes:编码前的字节序列。

可以认为字符串有两种状态,即文本状态和字节(二进制)状态。Python2和Python3中的两种字符类型都分别对应这两种状态,然后相互之间进行编解码转化。编码就是将字符串转换成字节码,涉及到字符串的内部表示;解码就是将字节码转换为字符串,将比特位显示成字符。

在Python2中,str和unicode都有encode和decode方法。但是不建议对str使用encode,对unicode使用decode, 这是Python2设计上的缺陷。Python3则进行了优化,str只有一个encode方法将字符串转化为一个字节码,而且bytes也只有一个decode方法将字节码转化为一个文本字符串。

print:Python2中的print是语句;Python3中的print是函数。

例如:

py2

print("hello", "world") ('hello', 'world') ​

py3

print("hello", "world") hello world

`` `This example is more obvious in py2 in contact behind the print statement is a tuple object, in py3, the print function may receive a plurality of location parameters. If you wish to print function when used in Python2, then the module may be introduced in the future print_function.

import: python2 default import module and packages, python3 default path is introduced in absolute accordance with the relative path.

import understanding: python2 python3 and distinguished by the import module and import the package

input: Python3: input str parse input character; Python2: input parsing an input to an int, raw_input parse input str type.

Arithmetic operators: In Python2 in / executed traditional division for division by truncation integer execution, floating-point numbers floating-point division (the fractional part retained, even divisible); // perform division Floor, cut and remove the remainder returns an integer operands for integer, if any operand is a floating point number, a floating-point number is returned. In Python3, the / real division is always executed, regardless of the type of operand, will return floating-point results that contain any of the remainder; // Perform Floor division, cut and remove the remainder returns an integer for integer operands, if there is any floating point operand is a floating point number is returned.

int / long: Python3, the only one integer type int, in most cases, it is much like Python2 in long integer. Python2 have non-floating-point type int and long prepared. Int type can not exceed the maximum sys.maxint, and the maximum value is platform-dependent.

True and False: In the Python2, True and False are two global variables (name), corresponding in value to 0 and 1, since it is variable, then they can point to other objects. Python3 fixes this flaw, True and False become two keywords, always point to two fixed objects, not allowed to be reassigned.

Iterator: Python2 in many built-in functions and the method returns the list of objects changed are returned Python3 similar iterator object because lazy loading characteristics iterator such large data operation more efficient.

For example: Python2 used xrange () to create an iterator object, use the range () to create a list array (sequence of numbers to generate a lot of the time, with a range xrange will be much more than excellent performance, because no one up on the open a lot of memory space); Python3 use range () to create an iterator objects, removed xrange () method.

In addition, dict.keys dictionary objects (), dict.values () method no longer returns a list, but with a view like object iterator returns. Higher-order functions map, filter, zip return is also not a list of objects. Python2 iterator method must implement the next, and Python3 changed iter (), next.

nonlocal: In Python2 can use the keyword global can declare a variable as global variables inside a function, but in a nested function, you want to give a variable declared as non-local variables are not implemented in Pyhon3, new keyword nonlcoal, it is generally used in a closed package, so the same variables are variables outer layer.

LEGB scope of understanding: python3 of local, global, nonlocal Dynasty.

Wen source network for study purposes, if infringement contact deleted.

Published 38 original articles · won praise 1 · views 2178

Guess you like

Origin blog.csdn.net/wulishinian/article/details/105012415