开通博客我用的理由是:读书学习时记笔记,一方面为了回顾,一方面为了督促自己。fighting!
学习Python,我买了Python编程从入门到实践。
我将从第二章开始记录我认为我以后会忘记以及重要的知识点。
第2章:变量和简单数据类型
1、在程序中可随时修改变量的值,而Python将始终记录变量的最新值。
2、变量名不能包含空格,但可使用下划线来分隔其中的单词。
3、title():将每个单词的首字母都改写成大写。 upper():将每个字母都改成大写 lower():将所有字母改为小写
4、Python使用加号(+)来合并字符串。
例子:first_name="ada"
last_name="lovelace"
full_name=first_name + " " + last_name
print("Hello, " + full_name.title() + "!")
输出:Hello, Ada Lovelace!
5、空白泛指任何非打印字符,如空格、制表符和换行符。 \t:制表符(tab键) \n:换行符 字符串“\n\t”让Python换行到下一行,并在下一行开头添加制表符。
6、要确保字符串末尾没有空白,可使用方法rstrip()。调用方法rstrip()这种删除只是暂时的,再次访问变量时,变量未改变。要永久删除这个字符串空白,必须将删除操作的结果存回变量中。
>>> study_language=\'python \'
>>> study_language=study_language.rstrip()
>>> study_language
\'python\'
rstrip():删除末尾空白 lstrip():删除开头空白 strip():删除开头和末尾空白。
7、在用单引号括起来的字符串中,如果包含撇号,将导致错误。这是因为Python将第一个单引号和撇号之间的内容视为第一个字符串,而将余下的文本视为Python代码。
>>> message = \'One of Python\'s strength is its diverse community.\'
File "<stdin>", line 1
message = \'One of Python\'s strength is its diverse community.\'
^
SyntaxError: invalid syntax
改正:
>>> message = "One of Python\'s strength is its diverse community."
>>> print(message)
One of Python\'s strength is its diverse community.
8、Python2中,print语句的语法与Python3语法稍有不同,Python2中无需将要打印的内容放在括号内。在Python2代码中,有些print语句包含括号,有些不包含。我下载的是Python3。
9、p24页动手试一试 2-5
>>> message=\'\'\'Albert Einstein once said,"A person who never made a mistake neve
r tried anything new."\'\'\'
>>> print(message)
Albert Einstein once said,"A person who never made a mistake never tried anythin
g new."
10、Python使用两个乘号表示乘方运算:
>>>3**3
27
11、小数点可以出现在数字的任何位置,结果包含的小数位数可能是不确定的:
>>> 3*.1
0.30000000000000004
>>> 0.2 + 0.1
0.30000000000000004
12、使用str()避免类型错误
>>> age = 23 #这个变量可能表示数值23,也可能表示字符2和3.
>>> message = "Happy " +str(age) + "rd Birthday!"
>>> print(message)
Happy 23rd Birthday!
13、在Python2中,
>>> 3/2
1
>>> 3.0/2
1.5
在Python3中,
>>> 3/2
1.5
>>> 3.0//2
1.0
>>> 3//2
1
int()为向下取整,int(5.5)=5
14、在Python中,注释用井号(#)标识。
15、Python之禅
>>> import this
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!
>>>