您的位置:首页 > 编程语言 > Python开发

Python 学习(2):基础知识点

2017-09-24 10:31 405 查看
简单回顾python中的程序控制语句和字典操作,因为类似于其他语言的语法。所以只做简单记录!

if 判断

传统条件判断

语法与其他语言相似,简单一笔带过

# 简单的判断
test = ['aa','bb','cc','dd','ee','ff']
for element in test:
if element == 'cc':
print(element,'is equal to cc')
else:
print(element,'is not equal to cc')

# 这里的比较是区分大小写的。如果忽略大小,可以如下操作
test_element = 'AA'
print(test_element.lower() == 'aa')   # 返回是True

# 检查不相等
print(test_element != 'BB')     # 两个字符不相等 返回True

# 数字大小的比较
age = 18
print((age < 21))     # True
print((age > 21))     # False
print((age == 21))    # False

# 检查多个条件  与用 and  或用 or
print((age<20 and age >15))
print((age<20 or age >18))

# 检查是否包含
print('aa' in test)
print('AA' in test)


if 判断格式

# if
if condition:
pass

# if-else
if condition:
pass
else:
pass

# if-elif-else
if condition1:
pass
elif condition2:
pass
else:
pass


字典

举例

dic_test = {'key1':'aa','key2':'bb','key3':'cc','key4':'dd'}
print(dic_test['key2'])


输出

bb


字典以键值对的形式储存数据。用户通过
key
可以访问其对应的
value


添加

dic_test = {'key1':'aa','key2':'bb','key3':'cc','key4':'dd'}
dic_test['key_add'] = 'add'


修改

dic_test['key1'] = 'AA'


删除

del dic_test['key_add']


通过
Key
删除键值对

遍历

dic_test = {'key1':'aa','key2':'bb','key3':'cc','key4':'dd'}

for key,value in dic_test.items():
print('key:' + key)
print('value:' + value + '\n')


通过
items()
方法迭代 ,值得注意的是,items()仅仅保证key-value 的关系进行迭代。如果需要按照顺序迭代。则需要使用sorted()方法来进行迭代

for key in sorted(dic_test.keys()):
print('key:'+ key)
print('vakue:' + value + '\n')


while 循环

形式

while condition:
pass


python 中
while
的用法和其他语言的语法相似。同时循环中支持加入
break
continue
来跳出全部循环和跳过本次循环。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python