for()循环 详解 及 代码


本文地址: http://blog.csdn.net/caroline_wendy/article/details/17199977


Python的for()循环采用range的方式,迭代依次访问range的值, 但是无法修改range的范围和迭代的位置;

注意: xrange()在python3中, 已经被range()代替, 和xrange()的效果相同;

xrange具体参见:

python33文档: "range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists."

stackoverflow: http://stackoverflow.com/questions/17192158/nameerror-global-name-xrange-is-not-defined

如果想要改变循环次序, 最好使用while循环; 使用break可以终止for循环;

参见: http://stackoverflow.com/questions/14785495/how-to-change-index-of-for-loop-in-python

示例程序是一个猜名字的程序, 由于无法修改次序, 所以额外进行一次, 写成额外一次判断;


代码:

# -*- coding: utf-8 -*-    #====================  #File: abop.py  #Author: Wendy  #Date: 2013-12-03  #====================    #eclipse pydev, python3.3    name = 'Wendy'  friend = 'Caroline'  running = True #true首字母大写  times = range(1, 4)    print('Who is the author? ( you have 3 times)')    for i in times : #表示[1,4), 3个数, 1, 2, 3, for是顺次指向下一个元素, 无法更改i的值      guess = str(input("Enter an name(time: {0}) : ".format(i)))            if guess == name :           print('Congratulation, you guessed it! ')          break #循环终止      elif guess == friend : #额外的机会, 不能修改i的值, 改变判断次序          print('Oh, you know my friend! Give you one extra times! ')          guess = str(input("Enter an name(time: {0}) : ".format(i)))          if guess == name :               print('Congratulation, you guessed it! ')              break #循环终止'''      elif guess[0] != 'W': #elif的写法          print("Sorry, my first letter is 'W'. ")      else :          print("Please, continue to guess. ")  else : #while语句的else      print('Sorry, you have no times.')        print('done')  

输出:

Who is the author? ( you have 3 times)  Enter an name(time: 1) : Spike  Sorry, my first letter is 'W'.   Enter an name(time: 2) : Winny  Please, continue to guess.   Enter an name(time: 3) : Caroline  Oh, you know my friend! Give you one extra times!   Enter an name(time: 3) : Wendy  Congratulation, you guessed it!   done