发布: 江湖程序员 来源: 本站原创 时间: 2023/11/12 16:07
(410) 点赞: (116) 标签: 批量下载提速
第01-2节:python语法关键字、内置类型与内置函数
如何高效地学习python语言?.mp4
相信绝大多数初学者都会有这样一种疑惑,学习python编程要学的语法有哪些?要学的内置函数和类型有哪些?该如何去学?下面我用代码列出全部:
一、python语法关键字(共35个),敲以下代码运行即可输出:
print(__import__('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']
>>>
析:在实际编写的代码中python语法关键字是不带引号的,但用help(...)方法查看使用说明书时则须带上引号,
例如:
help('import')
输出结果:
The "import" statement
**********************
import_stmt ::= "import" module ["as" identifier] ("," module ["as" identifier])*
| "from" relative_module "import" identifier ["as" identifier]
("," identifier ["as" identifier])*
| "from" relative_module "import" "(" identifier ["as" identifier]
("," identifier ["as" identifier])* [","] ")"
| "from" module "import" "*"
module ::= (identifier ".")* identifier
relative_module ::= "."* module | "."+
...
Examples:
import foo # foo imported and bound locally
import foo.bar.baz # foo.bar.baz imported, foo bound locally
import foo.bar.baz as fbb # foo.bar.baz imported and bound as fbb
from foo.bar import baz # foo.bar.baz imported and bound as baz
from foo import attr # foo imported and foo.attr bound as attr
...
>>>
二、python自带类型与函数(共154个),敲以下代码运行即可输出:
print((lambda D:[D.__setitem__(i, eval(i)) for i in dir(__builtins__)] and D)(dict()))
或:
print((lambda D:[D.__setitem__(i, type(i)) for i in dir(__builtins__)] and D)(dict()))
输出结果:
{'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': , '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': }
>>>
析:在实际编写的代码中python自带类型与函数名称皆不带引号的,用help(...)方法可以查看自带类型或函数的使用说明书,
例如:
help(list)
输出结果:
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
| Built-in mutable sequence.
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
| Methods defined here:
| __add__(self, value, /)
| Return self+value.
| __contains__(self, key, /)
| Return key in self.
| __delitem__(self, key, /)
| Delete self[key].
| __eq__(self, value, /)
| Return self==value.
| __ge__(self, value, /)
| Return self>=value.
| __getattribute__(self, name, /)
| Return getattr(self, name).
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
| __gt__(self, value, /)
| Return self>value.
| __iadd__(self, value, /)
| Implement self+=value.
| __imul__(self, value, /)
| Implement self*=value.
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
| __iter__(self, /)
| Implement iter(self).
| __le__(self, value, /)
| Return self<=value.
| __len__(self, /)
| Return len(self).
| __lt__(self, value, /)
| Return self<value.
| __mul__(self, value, /)
| Return self*value.
| __ne__(self, value, /)
| Return self!=value.
| __repr__(self, /)
| Return repr(self).
| __reversed__(self, /)
| Return a reverse iterator over the list.
| __rmul__(self, value, /)
| Return value*self.
| __setitem__(self, key, value, /)
| Set self[key] to value.
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
| append(self, object, /)
| Append object to the end of the list.
| clear(self, /)
| Remove all items from list.
| copy(self, /)
| Return a shallow copy of the list.
| count(self, value, /)
| Return number of occurrences of value.
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
| Raises ValueError if the value is not present.
| insert(self, index, object, /)
| Insert object before index.
| pop(self, index=-1, /)
| Remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
| remove(self, value, /)
| Remove first occurrence of value.
| Raises ValueError if the value is not present.
| reverse(self, /)
| Reverse *IN PLACE*.
| sort(self, /, *, key=None, reverse=False)
| Sort the list in ascending order and return None.
| The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
| order of two equal elements is maintained).
| If a key function is given, apply it once to each list item and sort them,
| ascending or descending, according to their function values.
| The reverse flag can be set to sort in descending order.
| ----------------------------------------------------------------------
| Static methods defined here:
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
| ----------------------------------------------------------------------
| Data and other attributes defined here:
| __hash__ = None#__hash__方法为None的类型为可变类型、否则为不可变类型
>>>
析:list类型,即列表类型,可见__hash__ = None,所以列表类型是可变类型,在实际编写代码的列表对象形式为:
a = ['good', 520, '中国', 3.14159265]#这是列表类型的一个实例对象称之为列表对象(python中一切皆对象,对象即实例对象,python中默认每种类型皆可多次实例化,动态产生出多个实例对象)
列表对象的特点:前后方括号、中间每个元素以小写逗号分隔、可变类型、不可哈希。
上面这行代码中,等号前面的“a”为变量,写代码定义变量是为了便于追踪引用某个对象,变量的特点是以字母或“_”(下划线)开头,只能是由字母、下划线和数字组成。
代码后面的#号为标记注释,在代码中所编写的注释前要加上#号,代码中的注释不会影响代码的运行。
分别运行以下代码,即可分别输出常用类型的使用说明书:
help(str)#字符串类型
help(dict)#字典类型
help(tuple)#元组类型
help(set)#集合类型
help(int)#整数类型
help(float)#浮点数类型
作者:江湖程序员 (python帮助网)
转载请注明出处: www.pythonhelp.cn
---= 已经到底 =---