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

来源:互联网 发布:python reshape函数 编辑:程序博客网 时间:2024/05/22 10:27

简单回顾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 = 18print((age < 21))     # Trueprint((age > 21))     # Falseprint((age == 21))    # False# 检查多个条件  与用 and  或用 orprint((age<20 and age >15))print((age<20 or age >18))# 检查是否包含print('aa' in test)print('AA' in test)

if 判断格式

# ifif condition:  pass# if-elseif condition:    passelse:    pass# if-elif-elseif condition1:    passelif condition2:    passelse:    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的用法和其他语言的语法相似。同时循环中支持加入breakcontinue来跳出全部循环和跳过本次循环。

原创粉丝点击