Python學習筆記(一)——入門

學習環境是python shell2.7,也是目前最穩定和常用的版本吧

  娛樂階段

  學習python之前,先來看看python的設計哲學,我覺得Guido van Rossum一定是個有趣的人,能將設計思想展現在python解釋器中,呵呵。輸入import this 命令:

 

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32

Type "copyright", "credits" or "license()" for more information.

>>> 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.雖然這種 方式可能不容易,除非你是python之父

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!  命名空間是一種絕妙的理念,應當多加利用

>>>

  哈哈,和一般的語言不同,在“hello world”程序開始之前,它還有一番人生哲學啊。

    初步入門:

    第一個python程序:(和其他腳本一樣,可以按tab鍵快速選擇)

>>> print "hello world"    ==>print是一個函數

hello world

>>>

    這個在python3.0的解釋器中運行是錯誤的,應該寫成:print("hello world"),不管這些,以下均是2.X版本下。

  基礎知識:

  交互式python解釋器可以當非常強大的計算器使用 

>>> 1+1

2

>>> 1/2   ==>和其他語言一樣,不做任何處理的情況下,這個是取整

0

>>> 1.0/2  ==>將任意一個數寫成浮點形式,則結果會與精度最大的保持一致

0.5

>>> 1./2   ==>單獨寫個小數點也行

0.5

>>> 1//2   ==>   //這個符號是專門取整的

0

>>>

         假如不想每次都要這麼費勁一下,我就想在python裏執行普通的除法,有辦法:

>>> from __future__ import division   ==>注意future左右是兩個下劃線

>>> 1/2

0.5

>>> 1//2   ==>在這種情況下你反而想取整數部分了,使用//
>>> 0
>>>1.//2
>>>0.0

      長整型和進制:

>>> 958346283662845  ==>2.2版本以前是不能處理長整型的,範圍是-2147483648~2147483647

958346283662845L   ==>L表示長整型,而且是大寫

>>> 0xAF  ==>16進制

175

>>> 010   ==>8進制  010首數字是0,表8進制)

8

>>>

  獲取用戶輸入:

>>> x=input("x=")

x=3

>>> y=input("y=")

y=4

>>> x*y

12

     函數:

>>> pow(2,3)   ==>求冪函數

8

>>> 2**3

8

>>> abs(-10)   ==>取絕對值

10

>>> round(5/2) ==>這裏是先算5/2,即2,所以round(2)=2.0

2.0
>>> round(2.5) ==>把浮點數四捨五入爲最接近的整數值
3.0
>>> floor(32.9) ==>取爲不大於該數的最大整數
32

  模塊:

>>> floor(23.5)

==>出錯了

Traceback (most recent call last):  

  File "<pyshell#29>", line 1, in <module>

    floor(23.5)

NameError: name 'floor' is not defined

>>> import math   ==>引入模塊math

>>> math.floor(23.5)

23.0

>>> int(math.floor(23.5))  ==>轉換爲整數

23

>>>

   那我不想每次都輸入math.來調用相應函數,如下寫法:

>>> from math import floor

>>> floor(3.2)

3.0

  cmath和複數:

  在高中的時候有複數的預算,比如對一個複數取平方根,python提供了對複數處理的機制,但是要引入cmath模塊。

>>> sqrt(-9)

 

Traceback (most recent call last):

  File "<pyshell#35>", line 1, in <module>

    sqrt(-9)

NameError: name 'sqrt' is not defined

>>> import math   ==>引入math模塊也無效

>>> math.sqrt(-9)

 

Traceback (most recent call last):

  File "<pyshell#37>", line 1, in <module>

    math.sqrt(-9)

ValueError: math domain error

>>> import cmath  ==>引入cmath模塊

>>> cmath.sqrt(-9)

3j

>>> (1+3j)*(9-2j)  ==>還可以進行計算

(15+25j)

>>>

__future__這個模塊比較特別,它可以導入那些在未來會成爲標準python組成的新特性)

  保存並執行程序:

  現在建一個python文件,擴展名是.py,把 print "hello python!"寫入,雙擊,我們看到的是一閃而過的一個黑框,我記得在執行C#窗體程序的時候也會出現這種情況,只要在主程序結尾加上"Console.ReadKey()"就行了,這裏也是,要給控制檯一個提醒輸入的機會,不然運行完就退出了,在結尾加一個語句:raw_input()。再雙擊即可彈出“hello python!”

執行這個文件hello.py

name=raw_input ("what is you name:")

print "hello "+name +"!"

raw_input()

      字符串:

>>> "hello python!"   ==>雙引號會把原字符串按原樣顯示

'hello python!'

>>> "we'll go shopping!"

"we'll go shopping!"

>>> 'we'll go shopping!'

SyntaxError: invalid syntax

>>> 'we\'ll go shopping!'   ==>轉義單引號

"we'll go shopping!"

>>> "\"hello,python!\" she said"   ==>字符串本身有雙引號的情況

'"hello,python!" she said'

>>>"hello " + "python!"   ==>字符串拼接
'hello python!'

       str & repr:

  您可能發現了,不用print打印出的字符串顯示出來的時候會被單引號括起來。所有通過python打印的字符串是被引號括起來的,這是因爲python打印值的時候會保持該值在代碼中的狀態,而不是你希望用戶看到的狀態。

>>> print "hello world"

hello world

>>> print 'hello world'

hello world

>>> "hello world"

'hello world'

>>> 'hello world'

'hello world'

>>> print 10000L

10000

>>> 10000L

10000L

>>>

     這裏討論的實際是值轉換成字符串的兩種機制,

   str函數:會把值轉換爲較理性的字符串,以便用戶可以理解

   repr函數:會創建一個字符串,以合法的python表達式的形式表示值。

>>> print repr("hello python!")

'hello python!'

>>> print repr(100000L)

100000L

>>> print str("hello python!")    ==>顯然,用戶更希望看到的是str函數處理後的結果

hello python!

>>> print str(10000L)

10000

>>>

    其實python有時候也沒有這麼智能,在高級語言中,好像數字有時候可以自動轉換爲字符串型

>>> age=22

>>> print "my age is "+ age

 

Traceback (most recent call last):

  File "<pyshell#72>", line 1, in <module>

    print "my age is "+ age

TypeError: cannot concatenate 'str' and 'int' objects

>>> print "my age is "+ str(age)

my age is 22

>>>

   input & raw_input

      這樣,我們先運行兩個腳本,代碼如下:

name=input("please input your name:")

print "hello,"+name

 

另一個腳本是將上述input改爲raw_input

  運行會發現,第一個出錯。其實不運行腳本也行,我麼直接在解釋器裏運行命令吧!

>>> name =input("please input name:")

please input name:Jay

 

Traceback (most recent call last):

  File "<pyshell#74>", line 1, in <module>

    name =input ("please input name:")

  File "<string>", line 1, in <module>

NameError: name 'Jay' is not defined
>>> name =raw_input ("please input name:")
please input name:Jay

     其實你只要在input那個下面輸入的字符串加上引號就行了,這就是原因。input會假設用戶輸入的是python的合法表達式,當然以字符串作爲輸入的名字肯定沒有問題,但是要求用戶每次輸入一個東西還需要加引號,這不太友好。

  想反,raw_input函數會把所有的輸入當做原始數據,然後自動將其放入字符串中,所以不會出錯,所以我們應儘可能使用 raw_input()

     長字符串

  如果需要寫一個很長的字符串,它需要跨多行,可以使用三個單引號,強制換行用反斜槓\

>>> '''asdgh

agjaw

ag'''

'asdgh\nagjaw\nag'

>>> 1+5+\

      4+6

16

>>>

      python中對多個反斜槓(路徑中常用)轉義除了加\,可以在整個字串的前面加r

>>> print 'c:\temp\test.txt'  

c:    emp    est.txt      ==>\t是製表符,所以會將\t作爲一個製表符顯示

>>> print 'c:\\temp\\test.txt'   ==>用傳統的\轉義

c:\temp\test.txt

>>> print r'c:\temp\test.txt'    ==>在前面加r轉義

c:\temp\test.txt

>>>

     

      常用的函數:abs(number)cmath.sqrt(number)float(object)help()input(prompt)int(object)long(object)math.ceil(number)(返回上入整數)math.floor(number)(返回下舍整數)pow(x,y)raw_input(prompt)repr(object)str(object)round(number[.ndigits])

     

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章