条件控制语句if else
python是严格缩进的,基本格式:
a=True
if a:
print("yes")
else:
print("no")
a=1
b=2
if a==b:
print("yes")
else:
print("no")
判空操作也是很常用的
d=[]
if d:
print("yes")
else:
print("no") #结果为no
真实使用场景,用户输入账号密码
account='xinran'
password='123'
print('please account')
user_account=input()
print('please password')
user_password=input()
if user_account==account and user_password==password:
print("yes")
else:
print('no')
if可单独使用
pass是占位语句,在配合写代码时,先写框架,里面接口还没有实现,可先用pass占位
if True:
pass
if else嵌套
if condition:
if condition:
pass
else:
pass
else:
if condition:
pass
else:
pass
if elif
用 if elif代替switch
a=input()
a=1 print(1)
a=2 print(2)
a=3 print(3)
a什么都不是,则print('no'):
a=int(a)
if a==1:
print(1)
elif a==2:
print(2)
elif a==3:
print(3)
else:
print('no')
终端输入1,打印结果为 no,为什么呢?
终端输入的1,是字符串
所以代码中加入 a=int(a)
while循环
while True:
print(1)
如果条件为True,则会一直执行,陷入死循环
正常用法
count=1
while count<=10:
count+=1
print(count)
#加else
while count<=10:
count+=1
print(count)
else:
print("end")#在执行while结束之后,执行end
for循环
while与for的应用,一般是for比较多,但是递归情况下,用while就比较合适
for循环主要用于遍历序列或者集合,字典
a=['a','b','c','d']
for i in a:
print(i)
b=[['1','2','3','4'],('apple','banana','orange')]
for i in b:
print(i)
'''
['1', '2', '3', '4']
('apple', 'banana', 'orange')
'''
#如何让序列中所有元素进行输出
for i in b:
for j in i:
print(j)
'''
1
2
3
4
apple
banana
orange
'''
#如何横向全部输出
for i in b:
for j in i:
print (j,end='')
'''
1234applebananaorange
'''
#同时for循环也有else
for i in b:
for j in i:
print (j,end='')
else:
print("end")
'''
1234applebananaorangeend
在所有循环执行后,执行else,但else不常用
'''
break和continue
c=['1','2','3']
#如果2以后我都不想要了
for i in c:
if i=='2':
break
print(i)
#结果为 1,遇到break,会强制性退出循环,后面不再执行
#如果2不要,其他还想要
for i in c:
if i=='2':
continue
print(i)
#结果为 1 3,遇到continue,会强制性退出本次循环,后面继续执行
for i in c:
if i=='2':
break
print(i)
else:
print("end")
#结果为1,说明break结束循环之后,else里面内容不再执行
for i in c:
if i=='2':
continue
print(i)
else:
print("end")
#结果为1 3 end,说明continue结束循环之后,else里面内容还会执行
d=[['1','2','3','4'],('apple','banana','orange')]
for i in d:
for j in i:
if j=='2':
break
print(j)
else:
print("end")
'''
1
apple
banana
orange
end
'''
#要看清break结束的是哪一层循环
for i in d:
if '2' in i:#因为第一层循环是序列,所以这样写
break
for j in i:
print(j)
else:
print("end")
#什么都没打印出来
其他语言for(i=0;i<10;i++){}怎么表达
for i in range(0,10):
print(i)
#结果为0,1,2,3,4,5,6,7,8,9
for x in range(0,10,2):
print(x,end='')
#range函数中,0代表从0开始,到10结束,2表示步长为2
#0246810
#递减等差数列
for x in range(10,0,-2):
print(x,end='')
#108642
a=[1,2,3,4,5,6,7,8]
#如何输出1,3,5,7,
for i in range(0,len(a),2):
print(a[i],end='|')
#结果为 1|3|5|7|
#也可以用序列的方式去做
b=a[0:len(a):2]
print(b)
#[1, 3, 5, 7]