python第一章笔记_第一章 基础

* 参与除法的两个数中有一个数为浮点数,结果也为浮点数 如: 1.0 / 2, 1 / 2.0, 1.0 / 2.0

~~~ python

>>> print 1.0 / 2 # 结果 0.5

>>> print 1 / 2.0 # 结果 0.5

>>> print 1.0 / 2.0 # 结果 0.5

~~~

* 整数 / 整数, 计算结果的小数部分被截除,只保留整数部分(不会四舍五入) 如: 1 / 2

~~~ python

>>> print 1 / 2 # 结果 0

~~~

* 通常情况下只需要普通算法,即 1 / 2 = 0.5 ,方法如下:

➣ 在程序前加上 from __ future __ import division (__ future __ 前后是两个下划线)

➣ 或直接在解析器中执行它

~~~ python

>>> from __future__ import division

>>> print 1 / 2 # 结果 0.5

~~~

* 幂运算

~~~ python

>>> print 2 ** 3 # 结果 8

~~~

* 布尔类型(Boolean)

➣ False None 0 "" () [] {} 作为布尔表达式时,都被解释器看做False

~~~ python

>>> print True == 1 # 输出 True

>>> print False == 0 # 输出 True

>>> print bool(0) # False

>>> print bool(0.0) # False

>>> print bool("") # False

>>> print bool(()) # False

>>> print bool([]) # False

>>> print bool(None) # False

>>> print bool({}) # False

>>> print bool(1) # True

~~~

* 布尔运算

~~~ python

>>> print True + False + 42 # 输出 43

~~~

* 转换字符串的两种机制

➣ str()函数,把值转换为合理的字符串形式 ----- 常用此方式

➣ repr()函数,创建一个字符串

~~~ python

>>> temp = 10

>>> print 'The temperature is: ' + str(temp)

>>> print 'The temperature is: ' + repr(temp)

# 输出结果都是: The temperature is: 10

~~~

* 原始字符串输出 r

~~~ python

>>> print 'Hello\nWorld' # 结果会换行 因为\n是换行符

>>> print 'Hello''World'

>>> print 'Hello','World'

>>> print 'Hello World'

>>> print 'C:\nowhere'

# 此时如果想完整打印路径需要使用 r 原始字符标识

>>> print r'C:\nowhere'

>>> print r'C:\nowhere\\'

>>> print r'C:\nowhere' '\\'

>>> print r'Let\'s go!' # 输出 Let\'s go!

#或

>>> print 'C:\\nowhere' # 此方式不适合长字符串 如: C:\\nwhere\\bozz\\frozz 需要写很多反斜杠

~~~

运行结果:

![](https://box.kancloud.cn/4d41228683e35854df067072de949fd7_124x204.png)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值