模块引用, 一个py文件可以做一个模块, 通过__name__控制主块是否运行
-
if __name__ == '__main__':
-
print 'This program is being run by itself'
-
else:
-
print 'I am being imported from another module'
dir函数 列举模块的标识符(变量、函数、类等)
数据结构:
list使用中括号包含,逗号分隔 a = [1, 2, 3, 4, 5] 可以改变
元组使用圆括号包含,逗号分隔 b = (1, 2,3, 4) 不可改变
list的操作
-
#!C:\Python33
-
shoplist = ['apple', 'mango', 'carrot', 'banana']
-
-
for item in shoplist:
-
print (item)
-
-
shoplist.append('rice')
-
-
print('================')
-
for item in shoplist:
-
print (item)
-
-
print('================')
-
shoplist.sort()
-
for item in shoplist:
-
print (item)
-
-
print('================')
-
del shoplist[1:3]
-
for item in shoplist:
-
print (item)
-
-
结果
-
-
>>>
-
apple
-
mango
-
carrot
-
banana
-
================
-
apple
-
mango
-
carrot
-
banana
-
rice
-
================
-
apple
-
banana
-
carrot
-
mango
-
rice
-
================
-
apple
-
mango
-
rice
-
>>>
元组输出:
-
age = 22
-
name = 'name'
-
-
print ('%s is %d years old' % (name, age))
-
print ('Why is %s playing with that python?' % name )
-
-
结果:
-
-
-
>>>
-
name is 22 years old
-
Why is name playing with that python?
-
>>>
-
-
注意 格式化输出 中间没有逗号
字典 键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
-
#!C:\Python33
-
a = {1:'one', 2:'two'}
-
-
print('=======================')
-
-
for i,st in a.items():
-
print(" %d : %s" %(i, st))
-
-
-
print('=======================')
-
-
a[3] = 'three'
-
a[4] = 'four'
-
for i,st in a.items():
-
print(" %d : %s" %(i, st))
-
-
print('=======================')
-
-
del a[3]
-
for i,st in a.items():
-
print(" %d : %s" %(i, st))
-
-
结果:
-
=======================
-
1 : one
-
2 : two
-
=======================
-
1 : one
-
2 : two
-
3 : three
-
4 : four
-
=======================
-
1 : one
-
2 : two
-
4 : four
-
>>>
参考 -- 列表,元组, 如果直接赋值则使用同一个对象, 否则需要使用切片操作获取新对象
-
#!C:\Python33
-
a = ['one', 'two', 'three', 'fourth']
-
b = a
-
c = a[1:2]
-
del a[1]
-
-
print('=========b==============')
-
-
for i in b:
-
print(i)
-
-
print('==========c=============')
-
-
for st in c:
-
print("%s" %st)
-
结果:
-
>>>
-
=========b==============
-
one
-
three
-
fourth
-
==========c=============
-
two
-
>>>
阅读(1486) | 评论(0) | 转发(1) |