python中的简单while循环及逻辑运算符

一、while循环 
        while 条件:
            循环体(break, continue)

注:break 彻底结束循环

  continue 仅结束本次循环 

while循环的具体应用

  求1-2+3-5+5...99的所有数的和

count = 1
sum = 0
while count < 100:
    a = count % 2
    if a == 1:
        sum = sum + count
    else:
        sum = sum - count
    count = count + 1
print(sum)

二、运算符 and or not  
运算顺序: () => not => and => or  当出现相同的运算的时候 从左往右算

print(3 > 2 or 5 < 7 and 6 > 8 or 7 < 5)      # True
print(3 > 4 or 4 < 3 and 1 == 1)      # False
print(1 < 2 and 3 < 4 or 1 > 2)      # True
print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1)     # True
print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8)     # False
print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)     # False
print((not 2 > 1 and 3 < 4) or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)     # False

and:并且. 左右两端同时为真. 结果才能是真

or : 或者. 左右两端有一个是真. 结果就是真
not : 非. 取反,当结果为真时 则为假 当结果为假时 则为真 非真既假, 非假既真

当出现 x or y的时候, 判断x是否是0 如果x==0 则返回y 否则返回x

print(1 or 2)     # 1
print(0 or 2)     # 2
print(3 or 0)     # 3
print(4 or 0)     # 4

# 当出现 x and y 的时候, 和or完全相反 如果x==0 则返回x 否则返回y

print(1 and 2)   # 2
print(0 and 3)   # 0
print(3 and 0)   # 0
print(4 and 0)   # 0

猜你喜欢

转载自www.cnblogs.com/wangm-0824/p/10028527.html