Loading

Python细节知识点


返回 我的技术栈(Technology Stack)



判断数据类型的方法

x = 4
print(isinstance(x, int))  # 输出: True
print(isinstance(True, int)) # 输出: True

print(bool(1))  # 输出: True
print(bool(0))  # 输出: False
print(bool(True))  # 输出: True

原因:在Python中,bool类型为int类型的子类


Python变量定义的本质

Q:Python中变量定义的本质是什么?
A:Python变量是引用类变量。变量中存储的并不是“所赋的值”,而是其地址!


数据类型转换

Python在 运算过程中不会自动进行数据类型转换!但是,除了 int / float / bool / complex 类型之间!

"3"+2 ==>报错!
3+True ==>4
3+3.3 ==>6.3
3+(1+3j) ==>4+3j

删除变量 del

del i

注意:del是语句,不是函数。因此,写成del(i)会报错!


Python之父Guido推荐命名方式

  • 模块名和包名:

    • regex_syntax
    • py_compile
    • _winreg
  • 类名或异常名:

    • BaseServer
    • ForkingMixIn
    • keyboardInterrupt
  • 全局或者常量

    • MAX_LOAD
  • 其余(方法名,函数名,普通变量名)

    • my_thread
  • 私有类型

    • _ init _
    • _ new _

查看关键字的方法

import keyword
print(keyword.kwlist)
输出:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']



# 查看已定义的所有变量
x = None
print(dir())
输出:
['__annotations__', '__builtins__', '__cached__', '__doc__','__file__',
'__loader__', '__name__', '__package__', '__spec__', 'keyword', 'x']

一行多句,一句多行

i=20;print("hello")  # 一行多句

print("Hello\
world")  # 一句多行

链式赋值语句

i=j=2
相当于
j=2
i=j

is判断的是什么

x = 10
y = 20
print(x is y)   # 输出:False
print(x is not y)   # 输出:True

is运算符的功能:判断的是 是否 指向同一个引用!


内置函数

查看内置函数的方法:

print(dir(__builtins__)) # 输出: ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

bin() 将十进制转为二进制

x = 10
y = 20
print(x, y)  # 输出:10 20
print(bin(x), bin(y))  # 输出:0b1010 0b10100

pow() 方法返回 \(x^y\)(x的y次方) 的值。

print("pow(100, 2) : ", pow(100, 2))  # 输出:pow(100, 2) :  10000

math 模块

import math

print(math.sin(5/2))  # 输出:0.5984721441039564
print(math.pi)  # 输出:3.141592653589793
print(math.sqrt(2.0))   # 输出:1.4142135623730951

print(math.sqrt(-2))  # 报错!【求解负数的平方根时会报错!】

# 解决方案
import cmath
print(cmath.sqrt(-2))  # 输出:1.4142135623730951j

Python math 模块提供了许多对浮点数的数学运算函数。

Python cmath 模块包含了一些用于复数运算的函数。

cmath 模块的函数跟 math 模块函数基本一致,区别是 cmath 模块运算的是复数,math 模块运算的是数学运算。


for、while可以带else

sum = 0
for i in range(1, 4):
    sum += i
    print(i, sum)
else:
    print("ok!")

输出:
1 1
2 3
3 6
ok!
sum = 0
i = 0
while (i <= 5):
    sum += i
    i += 1
    print(i, sum)
else:
    print("ok!")

输出:
1 0
2 1
3 3
4 6
5 10
6 15
ok!

posted @ 2021-08-02 19:21  言非  阅读(95)  评论(0)    收藏  举报