循环结构
while循环
流程图:
语法格式:
while 条件语句:
循环体
示例代码
num=1
sum=0
while num<10:
sum = sum+num
print(sum)
num +=1
un_users = ['alice','brian','candace']
co_users=[]
while un_users:
cur_user = un_users.pop()
print("Verifying user:" + cur_user.title())
co_users.append(cur_user)
while co_users:
user = co_users.pop()
print(user,end=' ') #不换行输出
break continue
break语句立即退出while循环,跳出循环体
continue跳过本轮循环,执行下一轮循环
num=1;
while num<10:
if num==5:
break
print(num , end=' ')
num+=1
print()
x=0
while x<10:
x+=1
if x%2==0 :
continue
print(x,end = ' ')
输出结果:
for循环
for循环需要用到range()函数。
range()函数的作用是生成整数序列,由三个参数决定序列的大小和范围:起始值,终值和步长。是半开区间,不包括序列的终值。
实例代码
a = 'Hello Myworld'
for i in a:
print(i,end=" ")
print()
for j in range(10):
print(j,end=" ")
print()
sum=0
for x in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
sum += x
if x==15:
print(x,end=" = ")
print(sum)
else:
print(x,end=" + ")
for y in range(1,20,3):
print(y,end=" ")
实现冒泡排序 嵌套
a = [1,55,22,11,44,66,6666,23,56,87,45,5]
for i in range(0,12):
for j in range(i,12):
if a[i] >a[j]:
temp=a[i]
a[i] = a[j]
a[j] = temp
for k in range(0,12):
print(a[k],end = " ")