python基础知识(二)--判断,循环(is, is not, not, if,for, while)

1.概述

只需要掌握is, is not, not, if,for, while的用法,就可以很轻松的实现python中所有的判断语句,循环语句。

2.is, is not, not

  • 在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False,可以用 is 或者 is not 来准确区分它们
a = ""
if a is not None:
    print('not None')
if a is not False:
    print('not false')
if a is not {}:
    print('not {}')
  • 如果用not来计算的话,他们都是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

  • 可实现选择逻辑,三目运算
#if
a = ""
if a is None:
    print("None")
elif a is False:
    print("False")
else:
    print("else")
#三目运算
print('True') if a is "" else 'False'

5.for,while

  • continue,这次循环到此结束,开始执行下个循环。
  • break,整个循环都结束了。
  • else,是当整个循环都结束后,才执行。如果提前结束,则不执行。
#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)

你可能感兴趣的:(python基础知识(二)--判断,循环(is, is not, not, if,for, while))