一、变量
在python中不需要为变量制定数据类型。可以单行定义多个变量。
>>> a, b = 2, 3.4
>>> a
2
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> b
3.4
还可以这样进行解压赋值,前提是变量的数量必须跟序列或元组的元素数量一样,
>>> date = ('Forsk', 'China', 'Python')
>>> name, country, language = date
>>> name
'Forsk'
>>> country
'China'
>>> language
'Python'
>>>
>>> data = ['Forsk', (2018, 1, 11)]
>>> name, time = data
>>> name
'Forsk'
>>> time
(2018, 1, 11)
>>> name, (year, mon, day) = data
>>> name
'Forsk'
>>> year
2018
>>> mon
1
>>> day
11
若变量的数量和元素数量不一致,将产生一个异常,
>>> name, (year, mon) = data
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
如果只想要解压其中一部分的值,丢弃其他,可以这样做,
>>> _, (year, mon, day) = data
>>> year
2018
>>> mon
1
>>> day
11
如果元素数量太多时,我们不可能给每个元素都分配一个变量,可以这样然后丢弃_就可以了。
>>> record = ('Forsk', 'forskwill@gmail.com', '13131313131', '6676-6666')
>>> name, email, *phone_number = record
>>> name
'Forsk'
'forskwill@gmail.com'
>>> phone_number
['13131313131', '6676-6666']
使用*解压之后得到的变量永远是列表类型,不需要做类型检查。
如果我们想得到头尾的值,可以这样
>>> name, *information, phone_number = record
>>> name
'Forsk'
>>> phone_number
'6676-6666'
从键盘获取输入
python3中使用input()
二、运算符和表达式
可在python界面直接使用运算符操作
>>> 2 + 3
5
>>> 5 - 6
-1
>>> 2 * 3
6
>>> 4 / 3
1.3333333333333333
>>> 4 % 3
1
>>> 5 % 3
2
关系运算符和逻辑运算符
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
>>> 1 < 2
True
>>> 3 < 2
False
>>> True or False
True
>>> True and False
False
>>> not True
False
>>> not False
True
运算符的简写
>>> a = 2
>>> a += 3
>>> a
5
运算符表达式符合正常数学逻辑
>>> a = 9
>>> b = 12
>>> c = 3
>>> x = a - b / 3 + c * 2 - 1
>>> x
10.0
('/'除以得到是float)运算符表达式符合正常数学逻辑
三、类型转换
float(string)
int(string)
str(integer)
str(float)