上一篇介绍了Mac环境的安装,安装完之后,我们需要一个编辑器来写Python代码。为了便于学习,我们可以使用Python自带的IDLE,类似Xcode的playGround。就在Python3文件夹里,打开就行了。
这篇主要介绍数字的运算和赋值,新手入门整理和归类。
Python虽然是强类型语言,但是有自己的类型判断机制,所以我们无需判断数据类型。
整型、浮点型赋值:
a=1
>>> a
1
>>> b=1.2345
>>> b
1.2345
科学计算法赋值:
>>> c=1e5
>>> c
100000.0
>>> d=2e-3
>>> d
0.002
不同进制赋值:
二进制:0b
八进制:0o
十六进制:0x
>>> e=0b11
>>> e
3
>>> f=0o17
>>> f
15
>>> g=0x1a
>>> g
26
>>>
float 转int :是用int()函数就行转换,可以吧float转成int ,规律是舍弃小数部分。
>>> f=1.6
>>> int(f)
1
>>> f=-1.6
>>> int(f)
-1
str转int:这里要求字符串必须是int类型否则报错
>>> g="123abc"
>>> int(g)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
int(g)
ValueError: invalid literal for int() with base 10: '123abc'
>>> g="1.2345"
>>> int(g)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
int(g)
ValueError: invalid literal for int() with base 10: '1.2345'
>>> g="1234"
>>> int(g)
1234
总结: 同理int、str转float把int()函数换成float()函数即可。int、float转str 用str()即可。
>>> str(123)
'123'
>>> str(1.23)
'1.23'
>>> float(str(1.23))
1.23