Zeray Rice

..

Python學習筆記——(1)基本操作

昨天晚上突然蛋疼的想去學Python,就在Google隨便搜了一篇入門文章來看,而且是在linux下,默認帶的就有Python,直接上咯,花了一個小時左右看到Python的類別(class),然後寫下筆記記錄下來,這是第一篇,先寫一下Python的基本操作什麼的。

在終端下直接輸入python打開python的解釋程序。

1
2
3
4
5
fanzeyi@fanzeyi-Ubuntu:~$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

先说说简单的计算操作,加减乘除:

1
2
3
4
5
6
7
8
9
>>> 65535+2
65537
>>> 1234-4321
-3087
>>> 55*55
3025
>>> 99/3
33
>>>

和C語言的操作一模一樣,而且可以拿來做計算器用= =。

Python裏面,註釋是以#開頭的,可以單獨放一行或者放到代碼之後。

賦值也是和C也一樣,用等號鏈接,例如:

1
2
3
4
>>> a=33
>>> b=a+23
>>> b
56

不過,與C不同的是,Python中可以連等,例如

1
2
3
4
5
6
7
>>> a=b=c=33
>>> a
33
>>> b
33
>>> c
33

Python還支持混合數據類型運算,例如

1
2
3
4
5
6
>>> 4*2.5/8
1.25
>>> 5.6/3
1.8666666666666665
>>> 8.0/2
4.0

運算部分結束,下面說說Python對於字符串的操作

字符串一般用’ 單引號包括,黨字符串中有’號時可用雙引號代替,或者用\作爲轉儀符

1
2
3
4
5
6
7
8
>>> 'Zeray'
'Zeray'
>>> "Zeray's Laptop"
"Zeray's Laptop"
>>> 'Zeray\'s Laptop'
"Zeray's Laptop"
>>> "\"Hey!\""
'"Hey!"'

字符串鏈接可以直接用+號,重複的話可以用*號,例如:

1
2
3
4
5
6
>>> word="Zeray"
>>> word=word+" "
>>> word
'Zeray '
>>> word*5
'Zeray Zeray Zeray Zeray Zeray '

和C語言一樣,Python也可以用下標(同樣的,下標從0開始計算)來直接訪問字符,不過更強大的是可以用:來制定範圍,例如:

1
2
3
4
5
6
7
8
9
10
11
12
>>> word[1]
'e'
>>> word[2]
'r'
>>> word[0:2]
'Ze'
>>> word[2:4]
'ra'
>>> word[:3]
'Zer'
>>> word[2:]
'ray '

其中,[:3]表示[0:3],[2:]表示[2:len(word)],len(word)就是這個字符串的長度。

如果你指定的範圍超過了最大長度,也不會報錯,但是當你指定的不是範圍時,會出現錯誤,例如:

1
2
3
4
5
6
7
8
9
10
11
12
>>> word
'zeray'
>>> word[100:]
''
>>> word[:100]
'zeray'
>>> word[3:1]
''
>>>word[100]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

更強大的一點是,下表可以爲負數,意思就是從字符串的右邊開始算起,例如:

1
2
3
4
5
6
7
8
9
10
>>> word
'zeray'
>>> word[-1]
'y'
>>> word[-3:]
'ray'
>>> word[:-3]
'ze'
>>> word[-5:-3]
'ze'

需要注意的是,-0依舊是0。

如果是多行的字符串可以在行末加上\表示續行,和C語言一樣 \n表示換行。

1
2
3
4
5
6
7
>>> a="This is a test\n\
... And more\n\
... My name is Zeray"
>>> print a
This is a test
And more
My name is Zeray

如果是很長很長的字符串,用\n\未免有些麻煩,可以用”“”三個雙引號(或者單引號)括住,即可。

1
2
3
4
5
6
7
8
9
>>> test = """
... Hello World!
... Today is rainy.
... My name is Zeray."""
>>> print test

Hello World!
Today is rainy.
My name is Zeray.

這只是最基本的Python操作,後面還有更多需要學習的,先寫到這裏,剩下的以後再寫。

Comments