- 一、标识符
- 二、print()打印输出函数
- 三、input()输入函数
- 四、dir()函数
- 五、help()函数
- 六、type()函数 & isinstance()函数
- 七、行与缩进
- 八、pass空语句
标识符的命名规则以下:python
- 只能由 字母,数字 和 下划线 组成,且首字符必须为字母或下划线。
- 区分大小写,见名知意。
- 不可以与Python中的关键字重名。
上面的这个关键字指的是,Python程序中预先定义的一些词,能够经过「keyword
」模块的kwlist
函数查询全部关键字,代码以下:sql
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']
复制代码
在Python中能够经过print函数将信息打印输出到屏幕上,是验证代码执行结果最直观的体现,好比打印一句Hello Python到屏幕上:json
print("Hello Python")
复制代码
Python中的print函数很是强大,支持把各类类型的数据直接转成字符串的形式输出,也支持格式化输出,经过「%百分号」进行间隔,完整规则以下图所示:bash
使用代码示例以下:app
age = 18
print("您的当前年龄:%d" % age)
复制代码
Tips小技巧:async
print 默认换行,若是不想换行能够添加参数end,好比:print(xxx, end="")。编程语言
input函数能够从控制台获取用户输入的内容,以回车为结束,程序在读取时会自动忽略换行符,全部形式的输入按字符串处理。括号里能够写一些输入提示信息,示例以下:函数
name= input("请输入您的名字:")
print("您输入的名字是 %s" % name)
# 运行结果以下:
# 请输入您的名字:CoderPig
# 您输入的名字是 CoderPig
复制代码
dir函数能够「查看对象中的全部属性与方法」,好比能够经过下面的代码查看全部的内置函数:ui
import sys
print(dir(sys.modules['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', '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']
复制代码
经过上面的dir函数能够获取到全部的内置函数了,接着你还能够利用内置的help函数 来 查看函数或模块用途的详细说明,好比执行help(print),能够看到下面的说明信息:
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
复制代码
代码示例以下:
class A:
pass
class B:
pass
class C(A):
pass
if __name__ == '__main__':
a = A()
b = B()
c = C()
d = 60
print(type(a))
print(isinstance(a, B))
print(isinstance(c, A))
print("60是整形:", type(d) == int)
复制代码
代码执行结果以下:
<class '__main__.A'>
False
True
60是整形: True
复制代码
Python不像其余编程语言,能够经过大括号{}来对代码块进行划分,只能经过「缩进」来对语句进行「分组」,所谓的缩进就是每行代码前的「空白间隔」。相同的空白间隔表示这些语句处于同一个层次,so,正确的缩进显得很是重要,建议使用Tab来进行缩进。另外,若是你想「多个语句写到一行」,可使用 「;
分号」进行间隔。有时语句可能太长你还可使用「\
反斜杠」来衔接,而在[],{},()
里分行不须要反斜杠衔接!
表示不作任何事情,通常用做「占位语句」,以此保证格式或是语义的完整性。好比定义一个函数,大概做用是作啥的,可是具体逻辑尚不清晰,还没开始写业务代码,可使用pass空语句来占位,示例以下:
def Test():
pass
复制代码
若是本文对你有所帮助,欢迎
留言,点赞,转发
素质三连,谢谢😘~