内置操作
保留关键字
保留关键字(不能用作变量名)。
关键字 | 关键字 | 关键字 | 关键字 | 关键字 |
---|---|---|---|---|
and | as | assert | async | await |
break | class | continue | def | del |
elif | else | except | False | finally |
for | from | global | if | import |
in | is | lambda | None | nonlocal |
not | or | pass | raise | return |
True | try | while | with | yield |
pass
使用pass
语句可在代码块中告诉 Python什么都不要做。故 pass
语句还要充当一种占位符,可以提醒你在程序的某个地方什么都没有做,但以后可能要在这里做些什么。

input()
script
message = input("Tell me Something, and I will repeat it back to you: ") print(message)
output
Tell me something, and I will repeat it back to you: Hello everyone! Hello everyone!
使用
input()
时,PYTHON 将用户输入均解读为字符串:>>> age = input("How old are you? ") How old are you? 21 >>> age '21'
查看一个变量类型最直接的方式是用 type
函数。然后,若想检测一个变量是否为某种确定的类型,最好用isinstance()
函数,而不是使用 type()
函数。因为有时候不同的数据类型通常与一些基本数据类型共享一些属性,典型的例子就是 bool
类型是从更为通用的 int
类型派生而来的。
test = True
isinstance(test, bool) # True
isinstance(test, int) # True
type(test) == int # False
type(test) == bool # True
内置函数dir()
查找某模块定义的名称:其返回一个排序过的字符串列表
若无参数,
dir()
列出你当前定义的名称:注意:
dir()
不会列出内置函数和变量的名称,如果你想要这些,它们都定义在标准模块builtins
中:
进制转换
十进制整数与二进制、八进制或十六进制整数的转换(来源网络):
十进制向其他进制转换
>>> x = 1234 >>> bin(x) # 二进制 '0b10011010010' >>> oct(x) # 八进制 '0o2322' >>> hex(x) # 十六进制 '0x4d2'
其他进制向十进制转换
>>> int('0b10011010010', base=2) 1234 >>> int('10011010010', base=2) 1234
使用 format 函数使得结果不带
0b, 0o, 0x
前缀>>> x = 1234 >>> format(x, 'b') '10011010010' >>> format(x, 'o') '2322' >>> format(x, 'x') '4d2'
any(), all(), zip(), assert
any(iterable)
和 all(iterable)
会查看一个可迭代对象内容的逻辑值,any()
在可迭代对象中任意一个元素为真时返回 True,而 all()
在所有元素为真时返回 True.
zip(iterA, iterB, …)
从每个可迭代对象中选取单个元素组成元组列表并返回。它并不会在内存创建一个列表并因此在返回前而耗尽输入的迭代器;相反,只有在被请求的时候元组才会创建并返回,这种行为的技术术语叫惰性计算。
assert
(断言)用于判断一个表达式,在表达式条件为 False 的时候触发异常。断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况,例如我们的代码只能在 Linux 系统下运行,可以先判断当前系统是否符合条件。
aassert expression [, arguments]
等价于if not expression: raise AssertionError(arguments)
>>> assert True # 条件为 true 正常执行 >>> assert False # 条件为 false 触发异常 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> assert 1==1 # 条件为 true 正常执行 >>> assert 1==2 # 条件为 false 触发异常 Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError >>> assert 1==2, '1 不等于 2' Traceback (most recent call last): File "<stdin>", line 1, in <module> AssertionError: 1 不等于 2 >>>
字母与ASCII码转换
Python 中字母与 ASCII 码的转换:
函数 | 作用 | 示例 |
---|---|---|
ord() | 字符转 ASCII 码 | ord('A') # 65 |
chr() | ASCII 码转字符 | chr(65) # 'A' |
>>> help(ord)
Help on built-in function ord in module builtins:
ord(c, /)
Return the Unicode code point for a one-character string.
>>> help(chr)
Help on built-in function chr in module builtins:
chr(i, /)
Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.