检查Python版本
在命令行窗口检查 Python版本
python -V
Python 3.8.3
下载安装 Python
https://www.python.org/downloads/release/python-383/
安装
安装成功
认识程序
解释型语言
编译型语言
解释器
数字的数学运算
+ | 加法 | >>> 1+1 2 |
---|---|---|
- | 减法 | >>> 1-1 0 |
* | 乘法 | >>> 2*3 6 |
/ | 除法 | >>> 10/3 3.3333333333333335 |
// | 整除 | >>> 10//3 3 |
% | 取余 (取模) | >>> 10%3 1 |
** | 次幂运算 | >>> 2**10 1024 |
数据精度问题
>>> 0.1+0.2
0.30000000000000004
整数 int
整数(比如 2
、4
、20
)的类型是 [int](https://docs.python.org/zh-cn/3/library/functions.html#int)
,有小数部分的(比如 5.0
、1.6
)的类型是 [float](https://docs.python.org/zh-cn/3/library/functions.html#float)
。 在这个手册的后半部分我们会看到更多的数字类型。
浮点数 float
除法运算 (/
) 永远返回浮点数类型。如果要做 floor division 得到一个整数结果(忽略小数部分)你可以使用 //
运算符;如果要计算余数,可以使用 %
其它数字类型
除了 [int](https://docs.python.org/zh-cn/3/library/functions.html#int)
和 [float](https://docs.python.org/zh-cn/3/library/functions.html#float)
,Python也支持其他类型的数字,例如 [Decimal](https://docs.python.org/zh-cn/3/library/decimal.html#decimal.Decimal)
或者 [Fraction](https://docs.python.org/zh-cn/3/library/fractions.html#fractions.Fraction)
。Python 也内置对 复数 的支持,使用后缀 j
或者 J
就可以表示虚数部分(例如 3+5j
)。
练习
>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5 # division always returns a floating point number
1.6
>>> 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 # result * divisor + remainder
17
等号 (=
) 用于给一个变量赋值。然后在下一个交互提示符之前不会有结果显示出来:
>>> width = 20
>>> height = 5 * 9
>>> width * height
900
如果一个变量未定义(未赋值),试图使用它时会向你提示错误:
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
Python中提供浮点数的完整支持;包含多种混合类型运算数的运算会把整数转换为浮点数:
在交互模式下,上一次打印出来的表达式被赋值给变量 _
。这意味着当你把Python用作桌面计算器时,继续计算会相对简单,比如:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
字符串
Python 也可以操作字符串。字符串有多种形式,可以使用单引号('...'
),双引号("..."
)都可以获得同样的结果 。
>>> name = "小明"
>>> name
'小明'
>>> name = '小明'
>>> name
'小明'
>>> name = '小明)))****77777%%%%%%'
>>> name
'小明)))****77777%%%%%%'
>>> name = '小明说:'我爱学习''
File "<stdin>", line 1
name = '小明说:'我爱学习''
^
SyntaxError: invalid syntax
>>> name ="小明说:'我爱学习'"
>>> name
"小明说:'我爱学习'"
>>> name = '小明说:\'我爱学习\'' # \ 表示转义, \' 单引号当作普通字符串对待。
在交互式解释器中,输出的字符串外面会加上引号,特殊字符会使用反斜杠来转义。 虽然有时这看起来会与输入不一样(外面所加的引号可能会改变),但两个字符串是相同的。 如果字符串中有单引号而没有双引号,该字符串外将加双引号来表示,否则就加单引号。 [print()](https://docs.python.org/zh-cn/3/library/functions.html#print)
函数会生成可读性更强的输出,即略去两边的引号,并且打印出经过转义的特殊字符:
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.' # \n means newline
>>> s # without print(), \n is included in the output
'First line.\nSecond line.'
>>> print(s) # with print(), \n produces a new line
First line.
Second line.
如果你不希望前置了 \
的字符转义成特殊字符,可以使用 原始字符串 方式,在引号前添加 r
即可:
>>> print('C:\some\name') # here \n means newline!
C:\some
ame
>>> print(r'C:\some\name') # note the r before the quote
C:\some\name
字符串运算符
+运算符
+支支持 字符串+字符串
>>> 'xiaoming' + "xiaohong"
'xiaomingxiaohong'
不能与其它类型数据相加.
>>> 'xiaoming' + "xiaohong" + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
运算
字符串只能与数字(int)相乘
>>> "xiaoming"*10
'xiaomingxiaomingxiaomingxiaomingxiaomingxiaomingxiaomingxiaomingxiaomingxiaoming'
>>> "xiaoming"*"10"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>> "xiaoming"*2.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
练习
>>> print("*"*30,"\n","西瓜"," "*15, "$10","\n","可乐"," "*15,"$4","\n"+"*"*30)
******************************
西瓜 $10
可乐 $4
******************************
字符串操作
- len() 查看字符串的长度
>>> a = "abcdefg" >>> a 'abcdefg' >>> len(a) 7
索引
-6 -5 -4 -3 -2 -1 | | | | | | P y t h o n | | | | | | 0 1 2 3 4 5
>>> "Python" 'Python' >>> "Python"[0] 'P' >>> "Python"[1] 'y' >>> "Python"[10] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range >>> "Python"[-1] 'n' >>> "Python"[-2] 'o' >>> "Python"[-3] 'h' >>> "Python"[-100] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
切片
>>> "Python"[0:2] 'Py' >>> "Python"[0:3] 'Pyt' >>> "Python"[1:5] 'ytho' >>> "Python"[-3:-1] 'ho' >>> "Python"[-3:] 'hon' >>> "Python"[:3] 'Pyt' >>> "Python"[:] 'Python'
步进 step 步长
>>> w = "abcdefg"
>>> w[0:5:1]
'abcde'
>>> w[0:5:2]
'ace'
>>> w[0:5:3]
'ad'
步长的值为负数时,表示从右向左来取数据
>>> w[:5:1]
'abcde'
>>> w[:5:2]
'ace'
>>> w[-3:]
'efg'
>>> w[-3::2]
'eg'
>>> w[-3::-1]
'edcba'
>>> w[-1:-3:-1]
'gf'
>>> w[-1:-4:-1]
'gfe'
>>> w[::-1]
'gfedcba'
常用方法
>>> s = 'supercalifragilisticexpialidocious'
count() 统计某个字符在字符串中出现的次数
>>> s.count("s") 3
center(len,fill) 字符串满足长度,不够的部分用指定的字符串来填充。
>>> "coke".center(50,"*") '***********************coke***********************' >>> "coke".center(30,"*") '*************coke*************' >>> "coke".center(30,"=") '=============coke============='
index() 查找某个字符在字符串中的索引位置。
>>> s.index("a") 6 >>> s.index("a",6) 6 >>> s.index("a",7) 11 >>> s.index("a",12) 24 >>> s.index("a",25) #如果没有这个值,则报错 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
find() 找字符索引,如果没有找到,返回 结果 -1
>>> s.find('a') 6 >>> s.find('a',7) 11 >>> s.find('a',12) 24 >>> s.find('a',25) -1
upper() 转换大写
>>> s.upper() 'SUPERCALIFRAGILISTICEXPIALIDOCIOUS'
lower() 转化小写
>>> "HelloWorld".lower() 'helloworld'
strip() 默认去除两边空格, 加上参数,去除指定字符
>>> ' s '.strip() 's' >>> s 'supercalifragilisticexpialidocious' >>> s.strip('s') 'upercalifragilisticexpialidociou'
replace() 替换指定字符串
>>> s.replace('s','xiaoming') 'xiaomingupercalifragilixiaomingticexpialidociouxiaoming' >>> s 'supercalifragilisticexpialidocious' >>> s.replace('s','xiaoming',2) 'xiaomingupercalifragilixiaomingticexpialidocious' >>> s.replace('s','xiaoming',-2) 'xiaomingupercalifragilixiaomingticexpialidociouxiaoming' >>> s[::-1].replace('s','xiaoming',2) 'xiaominguoicodilaipxecitxiaomingiligarfilacrepus' >>> s[::-1].replace('s','xiaoming',2)[::-1] 'supercalifragilignimoaixticexpialidociougnimoaix' >>> s[::-1].replace('s','xiaoming',2)[::-1].replace("gnimoaix",'xiaoming') # 最后两个s 替换为xiaoming 'supercalifragilixiaomingticexpialidociouxiaoming'
字符串格式化
format 格式化
>>> "my name is {} ".format("xiaoming") 'my name is xiaoming ' >>> "my name is {} ".format("xiaowang") 'my name is xiaowang ' >>> "my name is {}, my age is {} ".format("xiaowang",20) 'my name is xiaowang, my age is 20 ' >>> "my name is {}, my age is {}, my sex is {} ".format("xiaowang",20,"nan") 'my name is xiaowang, my age is 20, my sex is nan ' >>> "my name is {name}, my age is {age}, my sex is {sex} ".format(age=20,sex="nan",name="xiaoming") 'my name is xiaoming, my age is 20, my sex is nan ' >>> "my name is {0}, my age is {1}, my sex is {2} ".format("xiaoming",20,"nan") 'my name is xiaoming, my age is 20, my sex is nan ' >>> "my name is {0}, my age is {2}, my sex is {1} ".format("xiaoming",20,"nan") 'my name is xiaoming, my age is nan, my sex is 20 ' >>> "my name is {0}, my age is {2}, my sex is {1} ".format("xiaoming","nan",20) 'my name is xiaoming, my age is 20, my sex is nan '
f 格式化
>>> name = "xiaoming" >>> age =10 >>> f"my name is {name}, my age is {age}"
【附录】