開通博客我用的理由是:讀書學習時記筆記,一方面為了回顧,一方面為了督促自己。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!
>>>