Python循环语句

来源:互联网 发布:手机淘宝购物 编辑:程序博客网 时间:2024/06/03 18:22
1.语法
   while 条件:

        代码块

   for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

 for iterating_var in sequence:   statements(s)


2.while循环嵌套

   while 条件1:
        条件1满足时,做的事情1
        条件1满足时,做的事情2
        条件1满足时,做的事情3
        ...(省略)...
        while 条件2:
            条件2满足时,做的事情1
            条件2满足时,做的事情2
            条件2满足时,做的事情3

            ...(省略)...

  在 python 中,while … else 在循环条件为 false 时执行 else 语句块:   

#!/usr/bin/python count = 0while count < 5:   print count, " is  less than 5"   count = count + 1else:   print count, " is not less than 5"以上实例输出结果为:0 is less than 51 is less than 52 is less than 53 is less than 54 is less than 55 is not less than 5



例:(1)猜拳游戏改成循环版,提示用户要不要再玩和要不要结束。
'''猜拳游戏改成循环版,提示用户要不要再玩和要不要结束。赢:   用户:123   电脑:312'''import randomflag = Truewhile flag:computer = random.randint(1,3)while True:user = int(input('请输入数字:(1)剪刀(2)石头(3)布:'))if user == 1:u = '剪刀'breakelif user ==2:u ='石头'breakelif user ==3:u='布'breakelse:print('请输入正确1,2,3中的任意数字。')if computer == 1:com = '剪刀'elif computer ==2:com ='石头'else:com='布'print('用户:%s  \n电脑:%s'%(u,com))if (user == 1 and computer == 3) or (user == 2 and computer == 1) or (user == 3 and computer ==2):print('赢了!')elif user == computer:print('平局!')else:print('输了!')while flag:str = input('是否继续游戏?[是,否]:')if str == '否':flag = Falsebreakelif str == '是':flag = Truebreak

3. for 循环

实例:#!/usr/bin/python# -*- coding: UTF-8 -*- for letter in 'Python':     # 第一个实例   print '当前字母 :', letter
4.循环的技巧

     1.在序列中循环时,索引位置和对应值可以使用 enumerate() 函数同时得到:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):...     print(i, v)...0 tic1 tac2 toe

     2.同时循环两个或更多的序列,可以使用zip()整体打包:

>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> for q, a in zip(questions, answers):...     print('What is your {0}?  It is {1}.'.format(q, a))...What is your name?  It is lancelot.What is your quest?  It is the holy grail.What is your favorite color?  It is blue.

     3.需要逆向循环序列的话,先正向定位序列,然后调用reversed()函数:

>>> for i in reversed(range(1, 10, 2)):...     print(i)...97531

     4.要按排序后的顺序循环序列的话,使用sorted() 函数,它不改动原序列,而是生成一个新的已排序的序列:

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):...     print(f)...applebananaorangepear

     5.若要在循环内部修改正在遍历的序列(例如复制某些元素),建议您首先制作副本。在序列上循环不会隐式地创建副本。切片表示法使这尤其方便:

>>> words = ['cat', 'window', 'defenestrate']>>> for w in words[:]:  # Loop over a slice copy of the entire list....     if len(w) > 6:...         words.insert(0, w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']