python3自学之路-笔记9

python3自学之路-笔记9_循环结构的使用

python3有两种循环结构,while和for

while的用法:

第一种:死循环

while True:
  print('循环中。。')

根据条件打破死循环,用break:

a=0
while True:
  a+=1
  print(a)
  if a==10:
    break

第二种:条件循环:

a=0
while a<10:
  a+=1
  print(a)
else:
  print('循环完毕')

其中else语句为循环条件不满足时执行。循环完毕后自动终止程序,不需要break去打破

for的用法:

for可以用来遍历一个对象,该对象可以是字符串,列表,元组,集合,字典等等

#字符串遍历
str1='你好啊,世界'
for i in str1:
 print(i)

#列表遍历:
list1=['苹果','桃子','西瓜','香蕉','梨子']:
for in in list1:
  print(i)

猜你喜欢

转载自blog.csdn.net/qq_32394351/article/details/88379950
今日推荐