python基礎一

1.輸出:

>>> print ('Hello World!')


2.輸入:

>>> user = input('Enter login name: ')
Enter login name: oyzhx
>>> user
'oyzhx'

3註釋:

# 從 # 開始,直到一行結束的內容都是註釋。


4.運算符:+ - * / //  % ** < <= > >= == !=  <>(不等於) and or not 

"//":用作浮點除法(對結果進行四捨五入)

"**":乘方

5.數字 int,long,bool, float,complex(複數)

bool:True,False


6.字符串

加號( + )用於字符串連接運算,星號(* )則用於字符串重複

>>> tmpStr ='hello'
>>> tmpStr2= 'world'

>>> tmpStr + tmpStr2
'helloworld'
>>> tmpStr*3
'hellohellohello'


7.列表和元組

列表:列表元素用中括號( [ ])包裹,元素的個數及元素的值可以改變。(aList=[1,2,3,'haha'])

元組:元組元素用小括號(( ))包裹,不可以更改 (aTuple = (1,2,3,'try'))


8.字典

由鍵-值(key-value)對構成,值可以是任意類型的Python 對象,字典元素用大括號({ })包裹。

>>> aDict ={'name':'oy'}
>>> aDict['school'] ='csu'
>>> aDict
{'name': 'oy', 'school': 'csu'}


9.代碼塊及縮進對齊

代碼塊通過縮進對齊表達代碼邏輯而不是使用大括號,因爲沒有了額外的字符,程序的可讀性更高。而且縮進完全能夠清楚地表達一個語句屬於哪個代碼塊。

if語句

if expression1:
       if_suite
elif expression2:
      elif_suite
else:
      else_suite


while 循環:

while expression:
         while_suite


for循環:

Python 中的for 循環與傳統的for 循環(計數器循環)不太一樣, 它更象shell 腳本里的foreach 迭代。Python 中的for 接受可迭代對象(例如序列或迭代器)作爲其參數,每次迭代其中一個元素。

>>> for item in['name','age','school']:
print (item)


name
age
school


enumerate():

>>> foo = 'abc'
>>> for i,ch in enumerate(foo):
print (ch,'%d' %i)

a 0
b 1
c 2


10.列表解析:

可以在一行中使用一個for 循環將所有值放到一個列表
當中:
>>> squared = [x ** 2 for x in range(4)]
>>> for i in squared:
... print i
0
1
4
9


11.文件和內建函數open() 、file()

handle = open(file_name, access_mode = 'r')


12.錯誤和異常try-except

try:
    filename = input('Enter file name: ')
    fobj = open(filename, 'r')
    for eachLine in fobj:
          print (eachLine, fobj.close())
except IOError, e:
    print ('file open error:', e)


13.函數:

def function_name([arguments]):
      "optional documentation string"
       function_suite


14.類

class ClassName(base_class[es]):
      "optional documentation string"
      static_member_declarations
       method_declarations

構造函數:__init__  析構函數:__del__


15.模塊

導入模塊:import module_name


16.特殊字符

反斜線 ( \ ) 繼續上一行

分號 ( ; )將兩個語句連接在一行中

 冒號 ( : ) 將代碼塊的頭和體分開


17.對象是通過引用傳遞的。


18.多元賦值

>>> x, y, z = 1, 2, 'a string'


19.專用下劃線標識符

_xxx 不用'from module import *'導入
__xxx__系統定義名字
__xxx 類中的私有變量名


發佈了60 篇原創文章 · 獲贊 5 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章