第四部分python循环语句

#while循环

n=100

sum=0

counter=1

while counter<=n:

    sum=sum+counter

    counter+=1

print('1到%d之和为:%d'%(n,sum))

print('1到%d之和为:'%n,sum)


#无限循环

var=1

while var==1:

    num=int(input('输入数字:'))

    print('你输入的是:',num)

print('bye')


count=0

while count<5:

    print(count,'小于5')

    count=count+1

else:

    print(count,'大于等于5')


#for语句

languages=['a','b','c','d']

for x in languages:

    print(x)


#break跳出当前循环

sites=['google','baidu','runoob','taobao']

for site in sites:

    if site=='runoob':

        print('菜鸟教程!')

        break

    print('循环教程',site)

else:

    print('没有循环数据')

print('完成循环')


#range()遍历数字序列

for i in range(5,9):

    print(i,end=",")

else:

    print('didi')

for j in range(0,10,3):

    print(j,end=',')

else:

    print('lili')

sites=['google','baidu','runoob','taobao']

for i in range(len(sites)):

    print(i,sites[i])

list(range(5))


#break和continue语句及循环中的else子句

#第一实例:for-break

for letter in 'runoob':

    if letter=='b':

        print('找到了%s!'%letter)

        break

    print('字母为:',letter)

print('完成!')

#第二实例:while-break

var=10

while var>0:

    print('当前数值为:',var)

    var-=1

    if var==3:

        print('找到了:',var)

        break

print('bye!')

#第三实例:while-continue

for letter in 'runoob':

    if letter=='o': #字母为o跳过输出

        continue

    print('字母为:',letter)

print('完成!')


for n in range(2,10):

    for x in range(2,n):

        if n%x==0:

            print(n,'等于',x,'*',n//x)

            break

    else:

        print(n,'是质数')


#pass语句不做任何事情,用作占位语句

for letter in 'runoob':

    if letter=='o':

        pass

        print('pass语块')

    print('字母为:',letter)


#乘法口诀

for i in range(1,10):

    for j in range(1,i+1):

        print(str(i)+'*'+str(j)+'='+str(i*j)+'  ',end='')

    print('')


for i in range(9,0,-1):

    for j in range(1,i+1):

        print(str(i)+'*'+str(j)+'='+str(i*j)+'  ',end='')

    print('')

你可能感兴趣的:(第四部分python循环语句)