Python函数号不会影响它运行的次数吗?

时间:2014-12-05 02:48:21

标签: python function

如果我写:

def f(n):
    blah
f(x)

然后只要'x'是一个数字,f就会运行一次。例如我刚试过:

def f(n):
    c = 1
    print c
f(x)

'x'为0然后为10,两次输出均为'1'。数字'x'实际代表什么,以及如何让函数运行'x'次?

我现在已经通过解决方法解决了我的问题(我之前会发布这个问题,但显然我只限制每90分钟发布一次)但我仍然希望知道将来。

我的程序与此类似:

def f(n):
    m = 0
    c = blah
    if condition(c):
        m = 1
    d = line involving c that had to be run before the end of the function loop, but after the if statement
    f(m)
f(1)

但是输出保持循环,因为即使m = 0,f(0)仍然导致函数循环。我的解决方法是:

m = 0

def f(n):
    global m
    m = 0
    c = blah
    if condition(c):
        m = 1
    else:
        m = 0
    d = line involving c that had to be run before the end of the function loop, but after the if statement
    if m = 1:
        f(1)
f(1)

哪个工作正常(实际上,回头看看,我认为'd'确实不需要在if语句之后运行,所以如果条件(c)我就可以完成:f(1) ),但似乎多余。我不知道为什么我必须为f(n)指定一个数字,但如果我将其留空或输入一个字符串就无法运行。是否有一个不那么“笨拙”的解决方案?

(我对编程很陌生,所以请用相当简单的术语解释..!)

谢谢!

1 个答案:

答案 0 :(得分:3)

如果你想要运行多次,你只需要编写一些描述的循环。对于已知的已知数量,您可以使用for

def f(n):
    for i in range(n):
        print i+1, "Pax is awesome"
    print

x = 3
f(x)
f(x-1)
f(7)

运行该代码将为您提供:

1 Pax is awesome
2 Pax is awesome
3 Pax is awesome

1 Pax is awesome
2 Pax is awesome

1 Pax is awesome
2 Pax is awesome
3 Pax is awesome
4 Pax is awesome
5 Pax is awesome
6 Pax is awesome
7 Pax is awesome

如果要循环直到满足一般条件(而不是固定次数),则可以使用while而不是for

def f(n):
    while (n % 8) != 0:
        print n, "Pax is awesome"
        n += 1
f(3)

此循环将继续运行,直到n达到8的倍数:

3 Pax is awesome
4 Pax is awesome
5 Pax is awesome
6 Pax is awesome
7 Pax is awesome

你的解决方法似乎有点紧张,特别是在他们使用完全不必要的递归的意义上。

您应该将代码的清晰度作为主要目标(我将此优化称为可读性)。这样做会使您的代码不太可能包含错误,并且更容易维护。

相关问题