条件控制语句
# and or not
a =1
b = 2
c = 0
a and b # 判断and前后是不是真,真的话返回最后一个真的值,否者返回第一个假的值
2
a or b # 判断or前后有没有真值,有就直接返回,不再继续判断,否者判断到最后的值直接返回最后的值直接返回
1
c and b
0
b
2
type(0)
int
type(c)
int
bool(0)
False
not a
False
not b
False
not c
True
a < b < c
False
a < b
True
# > < !=
a !=b
True
a != c
True
bool(1)
True
bool(c)
False
a and True
True
0 and True
0
None == True
False
False == True
False
[] == True # 是两个等号,一个等号是赋值,两个等号是比较
False
() == True
False
1 ==True
True
# and or 优先级 什么时候用一个等号,什么时候用两个等号?
x = True
y = False
z = False
x or y and z # 说明and的优先级高于or
True
(x or y) and z
False
# is 和 ==判断真假
a = 1
b = a
c = 1
a is b
True
a is c
True
a == b
True
a ==c
True
id(a)
1486646336
id(c)
1486646336
id(b)
1486646336
e = 1000
f = 1000
e is f # python 自己判断的,当数值较大的时候,数就存放在不通的内存中,它们的id就不同了,
# is 比较的是变量的内存地址是否一样
False
number1 = [1,2,3]
number2 = number1
number3 = number1[:] # 深浅拷贝
number1 is number2
True
number1 is number3
False
id(number1)
2685722590088
id(number3)
2685722589000
id(number2)
2685722627720
number1 == number3
True
if 一家子
# any
number1
[1, 2, 3]
if any(x>2 for x in number1):
print('ok')
else:
print('no')
ok
# all
if all(x>2 for x in number1): # (x>2 for x in number1)里面竟然可以有>做判断
# 从列表number1中取出的x,然后与 2 进行比较
print('ok')
else:
print('no')
no
# in
if 1 in number1:
print('good')
else:
print('bad')
good
while 循环
- else
- break
- continue
循环的路上一定要学会刹车
# 先学刹车,要预设假的情况出现
a = 4
i = 0
while i < a:
print(i)
i += 1
0
1
2
3
while True: # 一直为真,需要在程序中设置中断,break应运而生,就是为了终止无限的循环
name = input('name(q为退出):')
if name == 'q':
print('bye')
break
else:
print(name)
name(q为退出):q
bye
a = 7
i = 0
while i < 6:
print(i)
i+=1
if i == 3: # 比较i 与 3
break #终止while循环
else:
print("what's wrong")
0
1
2
a = 7
i = 0
while i < 7:
print(i)
i += 1
if i == 3:
continue
else:
print('look')
0
1
2
3
4
5
6
look
for 循环
- else
- break
- continue
for i in range(5):
print(i)
0
1
2
3
4
for i in [1,2,3,4]:
print(i)
1
2
3
4
for i in {1,2,3,4}:
print(i)
1
2
3
4
my_dict = {'name':'coop','city':'beijing'}
for i in my_dict: # 对于字典,打印的是key
print(i)
name
city
for i in my_dict.keys(): # 同上
print(i)
name
city
for i in my_dict.values(): # 打印的是values
print(i)
coop
beijing
for i in my_dict.items(): # 打印的是items
print(i)
('name', 'coop')
('city', 'beijing')
for i,j in my_dict.items():
print(f'{i}:{j}')
name:coop
city:beijing
for i in range(10):
print(i)
if i == 3:
break
else:
print('end')
0
1
2
3
for in range(10)
for i in range(10):
print(i)
if i == 3:
break
else:
print('end')
0
1
2
3
for i in [1,2,3,4,5]:
if i == 3:
break
print(i)
else:
print('end')
1
2
for i in range(10):
print(i)
if i == 3:
break
else:
print('end')
0
1
2
3
for i in [1,2,3,4,5]:
if i == 3:
break
print(i)
else:
print('end')
1
2
for i in range(10):
if i == 3:
break
print(i)
else:
print('end')
0
1
2