Python中的迭代器(循环变量)

时间:2015-02-19 15:19:57

标签: python loops variables iterator

为了练习并更好地理解for循环,我设计了一个计算给定数字的阶乘的函数。除了迭代器(循环变量)的作用之外,我得到了很多东西。

这是我设计的功能:

def main():
    print("This program computes the factorial of a number!")
    n = eval(input("Enter a whole number: "))
    fact = 1
    for factor in range(n, 1, -1):
        fact = fact * factor
    print("The factorial of {} is {}!".format(n, fact))
main()

当我运行6的阶乘程序时,该函数打印: The factorial of 6 is 720!

我想了解程序用户给出的输入n对迭代器(循环变量)factor的作用和关系是什么?

为了测试这个,我删除了迭代器(循环变量)factor并用输入变量n替换它。

def main():
    print("This program computes the factorial of a number!")
    n = eval(input("Enter a whole number: "))
    fact = 1
    for n in range(n, 1, -1):
        fact = fact * n
    print("The factorial of {} is {}!".format(n, fact))
main()

当我运行与前一段代码相同的6阶乘的程序时,该函数会打印: The factorial of 2 is 720!

当我要求Python计算相同的阶乘数时,为什么我会得到两个不同的答案。显然,后一段代码有些不对,我认为这与输入变量n和迭代器(循环变量)factor之间的关系有关。

4 个答案:

答案 0 :(得分:3)

从您的工作代码开始:

def main():
    print("This program computes the factorial of a number!")
    n = eval(input("Enter a whole number: "))
    fact = 1
    for factor in range(n, 1, -1):
        fact = fact * factor
    print("The factorial of {} is {}!".format(n, fact))
main()

添加打印(protip:这是一个非常有用的调试技巧):

def main():
    print("This program computes the factorial of a number!")
    n = eval(input("Enter a whole number: "))
    fact = 1
    for factor in range(n, 1, -1):
        print(factor)  # Add this line
        fact = fact * factor
    print("The factorial of {} is {}!".format(n, fact))
main()

你应该看到这样的输出:

6
5
4
3
2
The factorial of 6 is 720!

如您所见,factor变量每次都会在循环中发生变化。它采用您指定的range()中的每个连续值。

当您将循环变量更改为n时,它会被这些值覆盖。

答案 1 :(得分:0)

在第二个程序中,当函数运行到print语句时,n已被for循环更改。因此,当n正在按照您期望的那样在循环中变化时,当您打印n时,它已被循环覆盖。

答案 2 :(得分:0)

  1. 覆盖变量:
  2. 用户输入值在n变量中定义。在第二个例子中,n再次在for循环中定义。所以变量n是覆盖的。 检查n变量的is。

    e.g。

    >>> n = 6
    >>> id(n)
    160708724
    >>> n = 2
    >>> id(n)
    160708772
    >>> 
    
    1. 当代码超出键盘值时,在类型转换期间使用异常句柄。
    2. e.g。代码想要从键盘编号。

      >>> try:
      ...    n = int(raw_input("Enter number:"))
      ... except ValueError:
      ...    print "Enter only number value."
      ... 
      Enter number:99
      >>> n
      99
      >>> type(n)
      <type 'int'>
      >>> try:
      ...    n = int(raw_input("Enter number:"))
      ... except ValueError:
      ...    print "Enter only number value."
      ... 
      Enter number:test
      Enter only number value.
      >>> 
      
      1. 与您的第二个示例相关:我只打印n
      2. 的值

        代码:

        def factorialGenerator():
            print("This program computes the factorial of a number!")
            while True:
                try:
                    n = int(raw_input("Enter a whole number: "))
                    break
                except ValueError:
                    print "Enter only digit."
        
            print "\nUser enter value %d and its id %s\n"%(n, id(n))
        
            fact = 1
            for n in range(n, 1, -1):
                print "In for loop value %d and its id %s"%(n, id(n))
                fact = fact * n
        
            print("\nThe factorial of {} is {}!".format(n, fact))
        
        
        if __name__=="__main__":
            factorialGenerator()
        

        输出:

        This program computes the factorial of a number!
        Enter a whole number: r
        Enter only digit.
        Enter a whole number: 6
        
        User enter value 6 and its id 142415988
        
        In for loop value 6 and its id 142415988
        In for loop value 5 and its id 142416000
        In for loop value 4 and its id 142416012
        In for loop value 3 and its id 142416024
        In for loop value 2 and its id 142416036
        
        The factorial of 2 is 720!
        

答案 3 :(得分:0)

尝试:

def main():
    print("This program computes the factorial of a number!")
    n = eval(input("Enter a whole number: "))
    fact = 1
    for n in range(1, n+1, 1):
        fact = fact * n
    print("The factorial of {} is {}!".format(n, fact))
main()

你的问题是你在6处覆盖n为2,在新范围内你将覆盖它,直到你达到所需的n值。