python学习笔记(1)

时间:2022-06-01 21:37:12

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
>>> aList
[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:
  if_suite
elif expression2:
  elif_suite
else:
  else_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;

 
0
1
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,