python安全开发基础篇–第三节
条件控制语句
条件判断 if
计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用if语句实现:
>>>age = 20
>>>if age >= 18:
print 'your age is', age
out:your age is 20
经典if … else… 语句
>>>age = 3
>>>if age >= 18:
print 'your age is', age
>>>else:
print 'your age is', age
out:your age is 3
经典if …elif …else 语句
>>> age = 10
>>> if age >= 18:
print "你是成年人"
>>> elif age< 6:
print '你是儿童'
>>> else:
print "你是青少年"
out:你是青少年
python 循环
Python的循环有两种,一种是for…in循环
>>> names = ['Michael', 'Bob', 'Tracy']
>>> for name in names:
print name
out: ...
>>> for x in [0,1,2,3,4,5,6]:
print x
out: ...
>>> for x in xrange(10):
print x
out: ...
for 循环还会应用到迭代器上面,暂时不做讲解
####python循环 while
while 后面为真值的适合,代表循环可以执行下去
>>> n=10
>>> while n >0:
print n
n=n-1
out: ...
字典
Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。
举个例子,假设要根据同学的名字查找对应的成绩,如果用list实现,需要两个list:
names = ['Michael', 'Bob', 'Tracy']
scores = [95, 75, 85]
如何让两个list互相之间有联系呢,使用字典
>>> d = {
'Michael': 95, 'Bob': 75, 'Tracy': 85}初始化一个字典
>>> d['Michael']
out:95
>>> d['Timo']=67 新增timo同学得了67分
>>> d['Jack'] = 90 新增jack等于90分
>>> d
out:{
'Michael': 95, 'Bob': 75, 'Tracy': 85,'Timo':67,'Jack':90}
字典的其他 方法
>>> dict.clear()删除字典所有元素
>>> dist.items()以列表方式遍历
>>> dist.keys()以列表形式返回key
>>> dist.values()以列表形式返回所有的值
>>> dist.update(dict2)连接两个类型相同的字典