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

简单回顾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的用法和其他语言的语法相似。同时循环中支持加入breakcontinue来跳出全部循环和跳过本次循环。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值