Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python函数号不影响它运行的次数?_Python_Function - Fatal编程技术网

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

Python函数号不影响它运行的次数?,python,function,Python,Function,如果我写: def f(n): blah f(x) 那么,只要“x”是一个数字,f将只运行一次。e、 g.我刚刚试过: def f(n): c = 1 print c f(x) “x”为0,然后为10,两次输出均为“1”。数字“x”实际代表什么?如何让函数运行“x”次 我现在已经解决了我的问题,我打算在早些时候发布这个问题,但显然我被限制在每90分钟发布一次,但我仍然想知道未来的情况 我的程序与此类似: def f(n): m = 0 c = blah

如果我写:

def f(n):
    blah
f(x)
那么,只要“x”是一个数字,f将只运行一次。e、 g.我刚刚试过:

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,f0仍然导致函数循环。我的解决办法是:

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)
这很好,事实上,回头看,我不认为需要在if语句之后运行'd',所以我可以只运行if condition c:f1,但它似乎是多余的。我不确定为什么我必须为fn指定一个数字,但如果我将其留空或输入一个字符串,它将无法运行。有没有一个不那么“笨拙”的解决办法

我对编程非常陌生,所以请用相当简单的术语解释一下


谢谢

如果你想让某个东西运行多次,你只需要编写一个描述的循环。对于已知的提前量,您可以使用:

运行该代码将为您提供:

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:

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

3 Pax is awesome
4 Pax is awesome
5 Pax is awesome
6 Pax is awesome
7 Pax is awesome
您的变通方法似乎有点紧张,特别是在使用完全不必要的递归的意义上


您应该将代码的清晰性作为首要目标,我称之为可读性优化。这样做将使代码不太可能包含bug,并且更易于维护。

哦,好吧,如果我将I放在范围n:。。。如果:n+=1或其他什么-那会起作用吗?虽然我猜,因为它在函数开始时只读取'for I in range n',if命令不会更改任何内容,函数仍然只运行一次。而且,我仍然不确定函数为什么首先需要一个参数,因为您可以只为范围x中的I写。。。?我想这样写会更容易,因为当你调用函数时?@Patrik,你不需要改变I,for-range循环会帮你做到这一点。就参数而言,这只是良好的编码习惯。您可能希望使用y或42从其他地方调用该函数。我将修改示例以显示这两个功能。但在我的程序中,我希望函数运行的次数取决于该函数中的if语句-因此,如果我在rangen中使用I,我知道我不需要更改“I”,但如果我希望函数再循环一段时间,我需要增加“n”。@Patrik,如果您事先不知道迭代次数,因为这可能不是您想要的。我在答案中添加了一些内容,以向您展示如何做到这一点。
def f(n):
    while (n % 8) != 0:
        print n, "Pax is awesome"
        n += 1
f(3)
3 Pax is awesome
4 Pax is awesome
5 Pax is awesome
6 Pax is awesome
7 Pax is awesome