天天看點

python學習筆記(1)

版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/3639694

python學習筆記(1)

1)** 表示“冥”

2)輸入函數 raw_input()

3)字元串操作:

>>> pystr='python'

>>> iscool='is cool!'

>>> pystr[0]

'p'

>>> pystr[2:5]

'tho'

>>> iscool[:2]

'is'

>>> iscool[3:]

'cool!'

>>> iscool[-1]

'!'

>>> pystr+iscool

'pythonis cool!'

>>> pystr+' '+iscool

'python is cool!'

>>> pystr*2

'pythonpython'

>>> ‘--------------------’

4)Lists和Tuples

Lists和Tuples的主要差別在于:Lists用中括号[]包圍,其元素和尺寸可以改變;而Tuples用圓括号包圍,且不能更新。是以,Tuples可以被認為是隻讀清單List。

其子集可以用[]和[:]分割,如同字元串那樣。

>>> aList = [1,2,3,4]

>>> aList

[1, 2, 3, 4]

>>> aList[0]

1

>>> aList[2:3]

[3]

>>> aList[2:]

[3, 4]

>>> aList[:3]

[1, 2, 3]

>>> aList[1]=5

[1, 5, 3, 4]

>>> aTuple=('robots',77,93,'try')

>>> aTuple

('robots', 77, 93, 'try')

>>> aTuple[0]

'robots'

>>> aTuple[2:]

(93, 'try')

>>> aTuple[:3]

('robots', 77, 93)

>>> aTuple[1]='abc'

Traceback (most recent call last):

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

  aTuple[1]='abc'

TypeError: 'tuple' object does not support item assignment

>>> aTuple[1]=5

5)Dictionaries

字典Dictionaries是Python的哈希表類型。由鍵值對組成,鍵Key可以是任意Python類型,但是值Value隻能是數字或字元串。字典封裝在尖括号{}内。

>>> aDict={}

>>> aDict['host']='earth'

>>> aDict['port']=80

>>> aDict

{'host': 'earth', 'port': 80}

>>> aDict.keys()

['host', 'port']

>>> aDict['host']

'earth'

6)代碼塊使用縮進

7)if語句

if expression:

  if_suite

else:

  else_suite

if expression1:

elif expression2:

  elif_suite

while expression:

  while_suite

---------

>>> counter=0

>>> while counter<5

SyntaxError: invalid syntax

>>> while counter<5:

 print 'loop #%d' %(counter)

 counter=counter+1

loop #0

loop #1

loop #2

loop #3

loop #4

8)for循環和内建的range()函數

Python的for循環類似于shell腳本的foreach疊代類型的循環。

>>> print 'I like to use the Internet for:'

I like to use the Internet for:

>>> for item in ['e-mail','net-surfing','homework','chat']:

 print item

e-mail

net-surfing

homework

chat

Python提供了内建的range()函數,産生一個清單。如下所示:

>>> for eachNum in range(6):

 print eachNum;

2

3

4

5

9)檔案和内建的open()函數

檔案通路是程式設計語言最重要的功能之一,它也是持久化存儲的重要手段。

怎樣打開一個檔案:

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

例子:

filename = raw_input('Enter file name: ')

file = open(filename, 'r')

allLines = file.readlines()

file.close()

for eachLine in allLines:

  print eachLine,