解释器像一个简单的计算器:输入表达式,就会给出答案。表达式的语法很直接:运算符 +
、-
、*
、/
的用法和其他大部分语言一样(比如,Pascal 或 C);括号 (()
) 用来分组。例如:
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
整数(如,2
、4
、20
)的类型是 int,带小数(如,5.0
、1.6
)的类型是 float。本教程后半部分将介绍更多数字类型。
Division (/
) always returns a float. To do floor division and get an integer result you can use the //
operator; to calculate the remainder you can use %
:
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # floored quotient * divisor + remainder
17
Python 用 **
运算符计算乘方 1:
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
等号(=
)用于给变量赋值。赋值后,下一个交互提示符的位置不显示任何结果:
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
如果变量未定义(即,未赋值),使用该变量会提示错误:
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "", line 1, in
NameError: name 'n' is not defined
Python 全面支持浮点数;混合类型运算数的运算会把整数转换为浮点数:
>>> 4 * 3.75 - 1
14.0
交互模式下,上次输出的表达式会赋给变量 _
。把 Python 当作计算器时,用该变量实现下一步计算更简单,例如:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
最好把该变量当作只读类型。不要为它显式赋值,否则会创建一个同名独立局部变量,该变量会用它的魔法行为屏蔽内置变量。
除了 int 和 float,Python 还支持其他数字类型,例如 Decimal 或 Fraction。Python 还内置支持 复数,后缀 j
或 J
用于表示虚数(例如 3+5j
)。
服务器租用托管,机房租用托管,主机租用托管,https://www.e1idc.com