第1章 基础知识
1.4. 数字和表达式
-
设置python执行普通除法(即浮点除法),程序前添加:from future import division
-
整除(即整形数除法)操作符://
>>>1.0/2.0 0.5 >>>1.0//2.0 0
-
幂运算符:**
>>>2**3 8
1.7. 获取用户输入
>>>input("The meaning of life: ")
The meaning of life: 42
42
1.9. 模块
定义:导入到Python以增强其功能的扩展。
导入方式 | 函数调用 |
---|---|
import 模块 | 模块.函数() |
from 模块 import 函数 | 函数() |
1.9.1. cmath和负数
模块cmath处理复数
1.9.2. 回到_future_
__future__模块导入将来可能成为python部分的特性
1.10. 保存并执行程序
1.10.2. 让脚本像普通程序一样执行
在python脚本首行添加如下代码:
#!/usr/bin/python2
其中,!后为python程序的绝对路径
1.10.3. 注释
"#"字符之后为注释内容
1.11. 字符串**
1.11.1. 单引号字符串和转义引号
-
"xxx"与’xxx’均可标识字符串
-
""与’'可相互嵌套,但是与自身嵌套解释器会解析错误,例如
#正确语法 >>> "hello, 'world'" "hello, 'world'" >>> 'hello, "world"' 'hello, "world"' #错误语法 >>> "hello, "world"" File "<stdin>", line 1 "hello, "world"" ^ SyntaxError: invalid syntax >>> 'hello, 'world'' File "<stdin>", line 1 'hello, 'world'' ^ SyntaxError: invalid syntax
其中,错误语法很好理解,由于解析器需要将""和’'两两配对,当出现自身嵌套的情况时,解析器会将相邻的"或’进行配对,导致错误。
-
转义字符 \。
1.11.3. 字符串表示
- str():值转换为合理性是字符串;
- repr():创建一个字符串,以合法的python形式表示值;
- repr(xxx) = `xxx` ,其中 ` 为反引号
1.11.4. input和raw_input的比较
-
input():假设输入的是合法的python表达式
#错误语法 >>> input("what's your name: ") what's your name: abc Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'abc' is not defined #正确语法 >>> input("what's your name: ") what's your name: "abc" 'abc'
可见,错误语法中,字符串abc未使用python合法格式(使用""或’'括起来),input无法辨认而出错。
-
raw_input():所有输入作为原始数据,放入字符串中
>>> raw_input("what's your name: ") what's your name: abc 'abc'
1.11.5. 长字符串、原始字符串和Unicode
-
长字符串:使用’’‘xxx’’'或""“xxx”"",其中xxx可以换行,可使用 ’ 或 ‘’,不必添加转义字符。
>>> print '''This is a very long string. ... It continues here. ... And it's not over yet. ... "Hello, world!" ... Still here.''' This is a very long string. It continues here. And it's not over yet. "Hello, world!" Still here. #其中,...为python解释器输出表示继续输入,可忽略。
-
原始字符串
1)不会将 \ 作为特殊字符处理
2)用法:r’raw string’
3)不可用 \ 结尾 -
Unicode字符串:u’unicode string’