当前位置: 首页 > 工具软件 > Whiley > 使用案例 >

Python程序中while循环用法详解

唐星晖
2023-12-01

Python程序中while循环用法详解

用于编写通用迭代结构,顶端测试为真就会执行循环体,并会多次重复测试直到测试为假后才执行循环后的其它语句。        

1、while循环语法格式:

1).while bool_expression:

           while_suite

    else:

          else_suite

2).while boolean_expression:

           while_suite

     if boolean_expression2: continue

          if boolean_expression3: break

      else:

          else_suite

2、用法示例:

例1:while基础格式示例,定义url,并逐行从开头处减少一个字符显示

In [27]: url = 'www.field.com'

In [28]: while url:

  ....:     print url

  ....:     url = url[1:]

  ....:    

www.field.com

ww.field.com

w.field.com

.field.com

field.com

ield.com

eld.com

ld.com

d.com

.com

com

om

m

例2:while基础格式示例,逐行打印“x= 0”到“x = 9”

In [29]: x = 0;y = 10

In [30]: while x < y:

  ....:     print "x = %d"% x

  ....:     x += 1

  ....:    

x = 0

x = 1

x = 2

x = 3

x = 4

x = 5

x = 6

x = 7

x = 8

x = 9

In [39]: x = 0;y = 10

In [40]: while x <y:

   print "x = %d" % x,

  ....:     x +=1

  ....: 

# print后用,结尾可以在同一行显示打印结果      

x = 0 x = 1 x = 2 x = 3 x = 4 x = 5 x = 6 x= 7 x = 8 x = 9

例3:while基础格式示例,自定义url,并逐行从结尾处减少一个字符显示

In [41]: url = 'www.field.com'

In [43]: while url:

  ....:     print " url is : %s" % url

  ....:     url = url[:-1]

  ....:    

 urlis : www.field.com

 urlis : www.field.co

 urlis : www.field.c

 urlis : www.field.

 urlis : www.field

 urlis : www.fiel

 urlis : www.fie

 urlis : www.fi

 urlis : www.f

 urlis : www.

 urlis : www

 urlis : ww

 urlis : w

例4:while-else格式示例,自定义url,并逐行从结尾处减少一个字符显示,且当循环执行结束后打印提示信息“Game over !”

In [44]: url = 'www.field.com'

In [45]: while url:

   print " url is : %s " % url

   url = url[:-1]

  ....: else:

  ....:     print "Game over !”

  ....:    

 urlis : www.field.com

 urlis : www.field.co

 urlis : www.field.c

 urlis : www.field.

 urlis : www.field

 urlis : www.fiel

 urlis : www.fie

 urlis : www.fi

 urlis : www.f

 urlis : www.

 urlis : www

 urlis : ww

 urlis : w

Game over !

例5:break用法示例:自定义url,逐行从结尾处减少一个字符显示,自定义if条件,当减少5个字符时结束打印。

In [46]: url = 'www.field.com'; x = 0

In [47]: while url:

  ....:     print url

  ....:     url = url[:-1]

  ....:     x += 1

  ....:     if x > 5:

  ....:         break

  ....: else:

  ....:     print "Reduce 5 chars,gameover!"

  ....:    

www.field.com

www.field.co

www.field.c

www.field.

www.field

www.fiel

#       break会跳出最内层的循环,所以else不会执行

例6:continue用法示例:自定义url,逐行从结尾处减少一个字符显示,自定义if条件,当减少5个字符时结束打印,并提示信息“Reduce 5 chars,game over!”

In [47]: while url:

  ....:     print url

  ....:     url = url[:-1]

  ....:     x += 1

  ....:     if x > 5:

  ....:         continue

  ....:     else:

  ....:         print "Reduce 5chars,game over!"

  ....:         break        

www.field.com

www.field.co

www.field.c

www.field.

www.field

Reduce 5 chars,game over!

#continue会跳到所处的最近层循环的开始处,即跳到while循环开始执行处。

#else代码块:循环正常终止才会执行;如果循环终止是由break跳出导致的,则else不会执行;

例7、while True语句用法示例:

In [48]: l1=[]

In [49]: while True:

  ....:     x = raw_input('PleaseInput An Char:')

  ....:     if x == 'q' or x =='quit':

  ....:         break

  ....:     else:

  ....:         l1.append(x)

  ....:        

Please Input An Char:a

Please Input An Char:b

Please Input An Char:c

Please Input An Char:d

Please Input An Char:q

In [11]: print l1

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

3、while循环练习:

练习1:逐一显示指定列表中的所有元素;

In [54]: l1 = [1,2,3,4,5];count = 0

In [55]: while count < len(l1):

  ....:     print l1[count]

  ....:     count += 1

  ....: else:

  ....:     print l1

  ....:    

1

2

3

4

5

[1, 2, 3, 4, 5]

In [56]: while l1:

  ....:     print l1[0],

  ....:     l1.pop(0)

  ....: else:

  ....:     print l1

  ....:    

1 2 3 4 5 []

练习2:求100以内所有偶数之和;

In [70]: count = 2;sum =0

In [71]: while count < 100:

  ....:     sum += count

  ....:     count += 2

  ....: else:

  ....:     print "sum is%d." % sum

  ....:    

sum is 2450.

练习3:逐一显示指定字典的所有键;并于显示结束后说明总键数;

In [89]: d1 = {'x':11,'y':22,'z':33,'k':44}

In [90]: d1.keys()

Out[90]: ['y', 'x', 'k', 'z']

In [91]: key = d1.keys()

In [92]: while key:

  ....:     print key[0]

  ....:     key.pop(0)

  ....: else:

  ....:     leng = len(d1)

  ....:     print "Dict d1 Lengis %d." % leng

  ....:    

y

x

k

z

Dict d1 Leng is 4.

练习4:创建一个包含了100以内所有奇数的列表;

In [94]: l1 = [];x = 1

In [95]: while x < 100:

  ....:     l1.append(x)

  ....:     x += 2

  ....: else:

  ....:     print l1

  ....:    

[1, 3, 5, 7, 9, 11, 13, 15,...,93, 95, 97,99]

In [96]: x = range(1,100,2)

In [97]: print x

[1, 3, 5, 7, 9, 11, 13, 15,..., 93, 95, 97,99]

练习5:逆序逐一显示一个列表的所有元素

In [162]: y = [1,2,3,4]; count = 0

In [163]: y.reverse()

In [164]: while count < len(y):

  .....:     print y[count]

  .....:     count += 1

  .....: else:

  .....:     leng = len(y)

  .....:     print " List yleng is %d,reverse show over." % leng

  .....:    

4

3

2

1

List y leng is 4,reverse show over.

练习6:列表l1=[0,1,2,3,4,5,6], 列表l2=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],以第一个列表中的元素为键,以第二个列表中的元素为值生成字典d1;

In [174]: l1 = [0,1,2,3,4,5,6];l2 = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];d1={};count = 0

In [175]: if len(l1) == len(l2):

  .....:     while count <len(l1):

  .....:         d1[l1[count]] =l2[count]

  .....:         count += 1

  .....:     else:

  .....:         print "Newdict d1 is %s." % d1

  .....: else:

  .....:     print "listKeyError!"

  .....:    

New dict d1 is {0: 'Sun', 1: 'Mon', 2:'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri', 6: 'Sat'}.

 

 类似资料: