今天安裝了Debian5,沒想到基礎安裝的情況下居然會有python,於是安裝試試這個傳說中的語言。
下面通過一系列簡單樣本來體驗,代碼可以直接粘貼儲存,都通過測試。
我參照pdf學習的,大家可以從這個地址下載pdf檔案.
案例1:
#用於注釋,但第一行#!也給程式指出本代碼是靠/usr/bin/python執行的,所以檔案名稱可以不是py
如果你樂意,你可以給helloworld.py 增加屬性X,這樣你可以把它改成任意的檔案名稱直接執行,如hello。
#!/usr/bin/python
#filename:helloworld.py
print '\n\tHello World! That\'s Python!\n'
#if you want the .py file to be executable:chmod a+x helloworld.py
案例2:
變數不用聲明可以直接賦值;if/elif/else語句不用包括判斷語句且以:結尾;
代碼#!/usr/bin/python
#filename:raw_input.py
number = 23 #here no
; but you can add ; either
guess = int(
raw_input("Enter an Integer:")); #string,can use
' or "
if guess == number: #notice: no
() and there's a
:
print 'Congratulations, you guessed it.'
print '(but you do not win any prizes!)'
elif guess < number:
print "No, It's a little higher than what you input."
else:
print 'No,It\'s a little lower than what you input.'
print "Done!";
案例3:猜數字遊戲,5次猜不對就退出
while迴圈,break跳出;省去了類似C語言的{}而改用對齊來決定語句塊
代碼#!/usr/bin/python
#filename:while.py
number = 23
Hitting =
False
loop = 5
while not Hitting:
guess = int(raw_input("Guess what(" + str(loop) +" times left):"))
loop = loop -1 ;
if loop == 0:
print "\tToo stupid, you lost!"
break;
if guess > number :
print "\tYour number is bigger than that."
elif guess < number:
print "\tYour number is littler than that."
else:
Hitting = True;
print "\tYou WIN, Excellent Baby!"
print "\t--===--[DONE]--===--"
#the Done statement is line to while, so running out of while then "Done" execute.
樣本4:函數,預設參數,有傳回值;DocString
代碼#!/usr/bin/python
#filename:function.py
def value(num =
3): #there's
default parameter.
'''Coded by Phoenix :
RET(X) = X^X''' #DocStrings
ret = 1;
for i in range(0,num): #notice, there is :
ret = ret * num
return ret
number = int(raw_input("Input a number:"))
print value()
print number**number
print value(number) #output the x^x, by the way, you can use: x**x
print value.__doc__ #output DocStrings