Python: 學習之路(3) - 基本數據類型: Numbers, Strings

學習一門新的編程語言,最基礎的部分大同小異。基本上均包括這幾個方面: 數據類型、常量與變量、操作符、函數、判斷語句、循環語句...等等。...

本文也主要對這幾個方面做簡要介紹。在此之前,先了解下Python與其他高級編程語言不大一樣的地方。

  1. Python中沒有main()函數的概念,從第一行開始,逐行解釋執行。
  2. 關於代碼塊,我的大括號呢?

Python使用縮進劃分代碼塊,而不使用大括號。實際上,Python程序員更喜歡稱之為"代碼組",而不是"代碼塊"。總之,大家瞭解下就可以了,二者在Python中一般是指同一含義。

代碼組很容易識別,因為它們總是縮進的,。需要特別注意的是: 不要在Python中混用製表符(Tab)和空格!!!

Python是按照縮進的空格數來解釋代碼的,如果使用Tab鍵來縮進,可能會帶來潛在的問題。如果習慣使用Tab鍵,建議在編輯器配置Tab鍵替換為4個空格

。對於Python程序員來說,這是約定俗成的做法。

事實上,大括號在Python中也是有用的,不過不是用來區分代碼塊,而是用來分隔數據,如:字典類型的數據。



下面進入正文部分,目前知識有限,後續如有新的有用的知識點,再進行補充。

  • Numbers
  • Strings
  • 常量與變量

其他複雜類型後續單獨更新~



  • Numbers 數值

int 整數, 比如: 1,20,1000, -3, 0

0x前綴表示16進制數, 比如:0x12=18, 0xff = 255

0o前綴表示8進制數,比如0o12=10, 0o77 = 63

float浮點數, 比如: 1.2, -4.5, 科學計數法表示: 1.23x10^9 存儲為:1.23e9,0.000015表示為:1.5e-5

bool 布爾型,值是True 或 False

complex複數

  • Strings 字符串

以單引號'或雙引號"括起來的任意文本,比如: ‘abc’ , "abc", 兩種都是正確的,字符串都只有'a', 'b', 'c'這三個字符。

字符串輸出時,注意使用轉義字符'\'.

<code>>>> 'I\'m OK.'  //使用轉義字符\,輸出單引號'
"I'm OK."
>>> "I'm OK." //或者使用雙引號
"I'm OK."
>>> "Tom\tMary\tJane\tPeter"  
'Tom\tMary\tJane\tPeter'
>>> print("Tom\tMary\tJane\tPeter") //在print函數里,\n才生效
Tom	Mary	Jane	Peter
>>> >>> "Tom\nMary\nJane\nPeter"
'Tom\nMary\nJane\nPeter'
>>> print("Tom\nMary\nJane\nPeter") //在print函數里,\n才生效
Tom
Mary
Jane
Peter
>>> #seperate long strings in multiple lines  //#+string開頭的表示註釋
>>> print("Lily and Lucy are good friends. They are in the same class.")
Lily and Lucy are good friends. They are in the same class.
>>>#使用三組單引號'''...'''或者三組雙引號"""..."""來進行拆行、分行輸出。
>>> print("""Lily and Lucy are good friends.
They are in the same class.""")
Lily and Lucy are good friends.
They are in the same class.
>>> print('''Lily and Lucy are good friends.
They are in the same class.''')
Lily and Lucy are good friends.
They are in the same class.
>>> print('''Lily
Lucy
Mary''')
Lily
Lucy
Mary
>>> /<code>

讀取字符串長度:

<code>>>> len('Hello')
5
>>> len("world!")
6/<code>

字符串裡的字符的索引關係如下:

Python: 學習之路(3) - 基本數據類型: Numbers, Strings

取自Python manual手冊中的示例

舉例說明:

<code>>>> word = 'Python'
>>> print(word)
Python
>>> word
'Python'
>>> word[0]
'P'
>>> word[2]
't'
>>> word[5]
'n'
>>> word[6]
Traceback (most recent call last):
  File "", line 1, in 
    word[6]
IndexError: string index out of range
>>> word[-1]
'n'
>>> word[-3]
'h'
>>> word[-5]
'y'
>>> word[-6]
'P/<code>

字符串的其他操作可以help(str)查看. 或者查看manual手冊。

<code>>>> help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
    __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 | .........//and so on/<code>
  • 常量與變量

這裡必須介紹下變量了。

顧名思義,與數學中的概念一致。變量可以通過變量名訪問,其值時可以改變的。常量的值不能被改變的。在C/C++中,我們一般用全大寫字母來定義常量。

而在Python中,不支持const, 不支持#define, enum, 其實並沒有嚴格意義上的常量。大多數人所以為的Python中的常量,基本上都是可以修改的。

幾個常用的內置常量了解下即可,比如:布爾值 True和False, 可以賦值給bool類型的變量;空值None,經常用於表示空值,給 None 賦值是非法的並會引發 SyntaxError。

下面我們來認識下變量。

Python中的變量不需要預聲明,在第一次使用變量時,變量就會立即存在。Python變量從所賦對象的類型得到自己的類型信息。

舉例說明:

<code>>>> a=1
>>> a
1
>>> b=c=a
>>> b
1
>>> c
1
>>> a=3
>>> a
3
>>> b
1
>>> c
1
 >>> name = 'May'
>>> print(name)
May
>>> alias = name
>>> print(alias)
May/<code>

先定義了一個變量a, 給它賦值為整數1, 然後用"b=c=1“, 給b和c賦值,都指向1這個對象。然後修改了a的值為3,結果是,只有a的值變了,b和c的值沒變,仍為1.

第二個例子,定義了一個對象name, 用字符串"May"賦值。

這是因為:Python中一切皆對象,此對象並不是C++/Java中的對象,有所不同的是,Python不需要創建類,才能創建對象。所以,Python基於對象,但不是純粹的面向對象。

在上例中,"May", 1, 3 皆是對象。在定義變量a的時候,它指向對象1,後來修改a的值,指向了對象3, 而b,c所指的對象並沒有發生改變,所以仍然指向對象1, 值沒變。

Python: 學習之路(3) - 基本數據類型: Numbers, Strings


相關鏈接:

上一篇:Python: 學習之路(2) - 起步

下一篇:Python學習之路(4) - 基本數據類型: Lists, Tuples


Never too late to learn...to be continued...


分享到:


相關文章: