第二章
如何使用变量
如何创建描述性变量名
如何消除名称错误和语法错误
什么是字符串
如何使用小写、大写、首字母大写的方式显示字符串
如何使用空白来显示整洁的输出
如何剔除字符串中多余的空白
如何使用整数和浮点数
使用数值数据时需要注意的意外行为
如何编写说明注释
变量和简单数据类型
变量
- 变量的命名和使用
- 变量命名规则
- 变量名只包含字母、数字、下划线,变量名可以用字母或者下划线开头,但不能以数字开头
- 变量名不能包括空格,可以使用下划线间隔单词
- 不能用
Python
关键字和函数名作为变量名 - 变量名应该简短又具有描述性
- 慎用字母
o
(因为容易和数字0
混淆
- 变量命名规则
字符串
字符串是一系列字符,在 python 中,用引号括起来的都是字符串,其中引号可以是单引号也可以是双引号
-
使用方法修改字符串的大小写
-
将每个单词的首字母改为大写
title()
name = "li zn cu" print(name.title()) Li Zn Cu
-
将字符串全部变为小写
lower()
-
将字符串全部变成大写
upper()
name = "Li Zn Cu" print(name.lower()) print(name.upper()) li zn cu LI ZN CU
-
-
合并(拼接)字符串
- 使用
+
合并字符串first_name = "Li" last_name = "zncu" fulll_name = first_name + " " + last_name print(full_name) Li zncu
- 使用
-
使用制表符或者换行符添加空白
- 制表符:
\t
- 换行符:
\n
- 制表符:
-
删除空白
- python能够找出字符串开头和末尾多余的空白
- 要确保字符串末尾没有空白可以使用方法
rstrip()
- 要确保字符串开头没有空白可以使用方法
lstrip()
- 要确保字符串两端没有空白可以使用方法
strip()
数字
-
整数
- 在
python
中可以对python进行加(+)、减(-)、乘(*)、除(/)运算 - 在
python
中可以使用**
表示幂运算
>>> 3 ** 2 9 >>>3 ** 3 27
- 在
-
浮点数
python
将待小数点的数字都称为浮点数- 浮点数进行运算后,结果包含的小数位数可能是不确定的,所有语言都存在这种问题,
python
会尽可能地精准表示结果
-
使用
str()
避免类型错误- 使用
str()
可以告知python
你希望将变量的类型转为字符串进行接下来的操作
- 使用
注释
注释是让你能够使用自然语言在程序中添加说明的东西
- 编写注释的方法
- 使用
#
#一个注释
- 使用
- 该编写什么样的注释
- 编写注释的主要目的是阐述代码要做什么,以及是如何做的
python
之禅
在解释器中输入 import this
就可以获得编写优秀 python
代码的指导原则
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!