Python學習筆記

 

  1. 1.1 程序輸出,print語句  
  2.     把一個字符串賦值給變量,僅使用變量名時,輸出的字符串是用單引號括起來的,其目的是爲了讓非字符串對象也能以字符串的方式輸出——即它顯示的是該對象的字符串表示,而不僅僅是字符串本身。  
  3. >>> myString = 'Hello World!' 
  4. >>> print myString  
  5. Hello World!  
  6. >>> myString  
  7. 'Hello World!' 
  8.     下劃線(_)在解釋器中有特別的含義,表示最後一個表達式的值。  
  9. >>> _  
  10. 'Hello World!'    
  11.     Python的print語句,與字符串格式操作符(%)結合使用。可實現字符串替換功能。  
  12. >>> print "%s is number %d!"%("Python",1)   
  13. Python is number 1!  
  14.     %s表示由一個字符串替換,%d表示由一個整型替換,另外%f表示由一個浮點型替換。  
  15.      Print語句也支持將輸出重定向到文件。符號>>用來重定向輸出。  
  16. >>> print >> sys.stderr,"Fital error:invalid input!" 
  17. Fital error:invalid input!  
  18. 1.2 程序輸入,raw_input()  
  19.     從用戶那裏得到數據輸入的最容易的方法是使用raw_input()內建函數(類似於SHELLl裏的read)。他讀取標準輸入,並將讀取到的數據賦值給指定的變量。可以使用int()內建函數將用戶的字符串轉換成整型。  
  20. >>> user = raw_input('Enter login name:')  
  21. Enter login name:root  
  22. >>> print 'Your login name:',user           
  23. Your login name: root  
  24. >>> num = raw_input('Now enter a number: ')   
  25. Now enter a number: 1024 
  26. >>> print 'Doubleing your number: %d'%(int(num)*2)    
  27. Doubleing your number: 2048 
  28.     在學習Python的過程中,如果需要得到一個生疏函數的幫助,只需對它調用內建函數help()。通過用函數名作爲help()的參數就能得到相應的幫助信息。  
  29. >>> help(raw_input)  
  30. Help on built-in function raw_input in module __builtin__:  
  31.  
  32. raw_input(...)  
  33.     raw_input([prompt]) -> string  
  34.       
  35.     Read a string from standard input.  The trailing newline is stripped.  
  36.     If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.  
  37.     On Unix, GNU readline is used if enabled.  The prompt string, if given,  
  38.     is printed without a trailing newline before reading.  
  39. (END)  
  40. 1.3 註釋  
  41.      同大部分腳本語言;一樣,Python也是用#標示注視,從#開始,知道一行結束的內容都是注視。  
  42. >>> #one monment  
  43. ... print 'Hello World!' 
  44. Hello World!  
  45. 1.4 操作符  
  46.      + - * / // % **  
  47.     加、減、乘、除(取比商小的最大整數)、浮點除(對結果四捨五入,是真正的除法)、取餘、乘方  
  48. >>> print -2*4+3**2 
  49. 1 
  50.     +和-優先級最低,*、/、//、%優先級較高,單目操作符+和-優先級更高,乘方的優先級最高。  
  51.      < <= > >= == != <> 標準比較操作符,根據表達式的值的真假返回布爾值。  
  52. >>> 2 < 43 
  53. True 
  54. >>> 2 <> 43 
  55. True 
  56. >>> 2 != 43 
  57. True 
  58.      !=和<>,均爲“不等於”比較操作符,後者慢慢被淘汰,故推薦使用前者。  
  59.       Python也提供邏輯操作符。  
  60.       and or not 
  61. >>> 2 < 43 and 2 > 34 
  62. False 
  63. >>> 2 < 43 or 2 > 34     
  64. True 
  65. >>> not 2 > 34         
  66. True 
  67. >>> 3<4<5 
  68. True 
  69.      最後一個例子在其他語言中通常是不合法的,不過Python支持這樣的表達式,級簡潔又優美。它實際上是下面表達式的縮寫:  
  70. >>> 3 < 4 and 4 < 5 
  71. True 
  72. 1.5 變量和賦值  
  73.  

 

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