1.概述
只需要掌握is, is not, not, if,for, while的用法弃锐,就可以很輕松的實(shí)現(xiàn)python中所有的判斷語句袄友,循環(huán)語句。
2.is, is not, not
- 在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都相當(dāng)于False,可以用 is 或者 is not 來準(zhǔn)確區(qū)分它們
a = ""
if a is not None:
print('not None')
if a is not False:
print('not false')
if a is not {}:
print('not {}')
- 如果用not來計(jì)算的話霹菊,他們都是False
if not a:
print("not a")
3.in
- 可用于字符串剧蚣,列表元素,字典鍵值判斷。
a = "shanghai"
my_lists = list(a)
my_dic = {"a":1,"b":2,"c":3}
print(a)
print(my_lists)
if "s" in a:
print("s in a")
if "a" in my_lists:
print("a in my list")
if "a" in my_dic:
print("a in my dic")
4.if
- 可實(shí)現(xiàn)選擇邏輯鸠按,三目運(yùn)算
#if
a = ""
if a is None:
print("None")
elif a is False:
print("False")
else:
print("else")
#三目運(yùn)算
print('True') if a is "" else 'False'
5.for,while
- continue礼搁,這次循環(huán)到此結(jié)束,開始執(zhí)行下個循環(huán)目尖。
- break馒吴,整個循環(huán)都結(jié)束了。
- else瑟曲,是當(dāng)整個循環(huán)都結(jié)束后饮戳,才執(zhí)行。如果提前結(jié)束测蹲,則不執(zhí)行莹捡。
#for
for i in range(10):
#continue
print(i)
if i == 9:
break
else:
print('the laste one is :%s'%i)
#while
sum10 = 0
i = 1
while i <= 10:
i += 1
#continue
sum10 += i
#break
else:
print(sum10)