简体   繁体   中英

Python, why does this function go into an infinite loop

def new_if (pred,then_clause,else_clause):

    if pred:
        then_clause
    else:
        else_clause

def p(x):
    new_if(x>5,print(x),p(2*x))

p(1)

I think the function should stop once x reaches 8 and 8 is printed out.

Thanks a lot for helping

Your code doesn't do what you think it does.

Every time you call p it executes the code inside that method, which in your case calls new_if with some arguments. However you are evaluating those arguments immediately, which means before entering new_if your code is executing print(x) and p(2*x) . This causes p to get called again, repeating the process.

There seems to be some general confusion in how you think your code is evaluated: in particular, what you think as predicates and clauses really are not. The arguments are evaluated before the call to new_if is made. Hence, you get a infinite recursive call to p , by evaluating p(2*x) almost as soon as you call p .

You could achieve what you want by passing functions, which you then evaluate within your new_if function. This can be done with lambda functions, like so:

def new_if (pred,then_clause,else_clause):
    if pred():
        then_clause()
    else:
        else_clause()

def p(x):
    new_if(lambda: x>5, lambda: print(x), lambda: p(2*x))

p(1)

In this case, pred , then_clause , else_clause are callables which you need to call ( () ) for them to be executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM