Skip to content Skip to sidebar Skip to footer

Python - What's The Use Of If True:?

I just came accross the following code in an existent project, which I'm working on: if True: x = 5 y = 6 return x+y else: return 'Something Inside the if True are

Solution 1:

It might be a remnant of debugging or refactoring. It may be that instead of True, there was orginally a condition or variable there but it has now been replaced by True. The developer perhaps left it there without refactoring or cleaning it up all the way.

If you're free to edit the code as you wish and you're sure that the else is no longer needed, then you can remove it. It indeed makes no sense to have code in your codebase that will never run.

Solution 2:

True doesn't necessarily mean True

True = Falseif not True :
    print"True is false"# This prints ok

Honestly, I don't think anyone would code like this.

Solution 3:

Does not make any sense to me, my guess is that someone wanted to have two distinct code paths that he could alternate between a'la using #if 1 .. #else -> #if 0 ... for debugging or such purposes.

Other possibility was that, as @SimeonVisser suggested, the original developer was refactoring or cleaning up the code (and did not have an emulator that allows one to easily remove 1 step of indentation from a block of code)

Solution 4:

It could be a flag used for debugging.

Solution 5:

It's simply used to ensure that the else: block is never executed. I have used if True: for some blocks to ensure that my code really does what I want. Usage for debugging or refactoring. All in all it makes no real sense to use this in an application but for testing or debugging it's somehow acceptable.

Post a Comment for "Python - What's The Use Of If True:?"