第一章
在windows终端运行Python程序:
C:\> cd Desktop\python_work
C:\Desktop\python_work> dir
hello_world.py
C:\Desktop\python_work> python hello_world.py
Hello Python world!
使用了命令cd
来切换到文件夹Desktop\python_work(见1)。接下来,使用命令dir
来确认这个文件夹中包含文件hello_world.py(见2)。最后,使用命令 python hello_world.py 来运行这个文件(见4)
第二章 变量和简单数据类型
变量
变量命名:
- 变量名只能包含字母、数字和下划线。变量名可以字母或下划打头,但不能以数字打头
- 变量名不能包含空格,但可使用下划线来分隔其中的单词
- 慎用小写字母l和大写字母O,因为它们可能被人错看成数字1和0
- 使用小写的Python变量名
程序无法成功地运行时,解释器会提供一个traceback。traceback是一条记录,指出了解释器尝试运行代码时,在什么地方陷入了困境。
字符串
在Python中,用引号括起的都是字符串,其中的引号可以是单引号,
也可以是双引号。
方法修改字符串大小写:
name="ada lovelace"
print(name.title()) # Ada lovelace
print(name.lower()) # ada lovelace 存储数据常用
print(name.upper()) # ADA LOVELACE
拼接字符串:
first_name='ada'
last_name='lovelace'
full_name=first_name+" "+last_name
print('Hello '+full_name.title()+"!")
message='Hello '+full_name.title()+'!'
print(message)
用制表符或换行符来添加空白:
print("Language:\n\tPython\n\tJavaScript\n\tC")
# \n 换行符 \t制表符
删除空白:
message="python "
print(message)
print(message.rstrip()) #暂时删除
print(message)
#永久删除需要将删除操作的结果存回变量
message=message.rstrip()
print(message)
message=" python "
print(message.lstrip()) #删除开头空白
print(message.rstrip()) #删除末尾空白
print(message.strip()) #删除两头空白
数字
Python使用两个乘号**
表示乘方运算。
浮点数包含小数位数可能不确定
print(0.2+0.1) #0.30000000000000004
print(0.1*3) #0.30000000000000004
类型错误:
age = 23
message = "Happy " + age + "rd Birthday!" #错误
message = "Happy " + str(age) + "rd Birthday!"
调用函数 str( ) ,将Python将非字符串值表示为字符串。
在Python 2中,整数除法的结果只包含整数部分,小数部分被删除,计算整数结果时,采取的方式不是四舍五入,而是将小数部分直接删除。(python 3保留小数)
注释
在Python中,注释用井号#
标识。
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!