Python - What's the use of if True:? - python

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 lots of conditions and some will also return the function already.
Why would somebody write in that way? The code contained some other bugs also, but was just wondering about the if True: statement as it didn't make any sense to me. Probably also pretty stupid to ask it, but was wondering hehe.

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.

True doesn't necessarily mean True
True = False
if not True :
print "True is false" # This prints ok
Honestly, I don't think anyone would code like this.

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)

It could be a flag used for debugging.

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.

Related

OWL2, SWRL: Query if item is in range of another item?

My problem is that if i want to check if an instance is in range, i use the following rule:
Rule1: Error(?d), TimeRelatedError(?c), TimeRelatedError_start_at(?c, ?s), error_at(?d, ?b), greaterThan(?b, ?s) -> is_after_TimeRelatedError_start(?d, true)
Rule2: Error(?d), TimeRelatedError(?c), TimeRelatedError_end_at(?c, ?e), error_at(?d, ?b), lessThan(?b, ?e) -> is_before_TimeRelatedError_end(?d, true)
It works if i have only one TimeRelatedError in my ontology, if i have more instances, it will always trigger true (because one of the TimeRelatedError are always before/after start/end point). Do you have any ideas how to solve this problem? I think i could tackle the problem if i assign my TimeRelatedError somehow to the Error instance but i do not know how. Please OWL/SWRL professionals help me with this task :)
I only can blame myself, i found a solution, only one rule with:
Error(?d), TimeRelatedError(?c), TimeRelatedError_start_at(?c, ?s), error_at(?d, ?b), greaterThan(?b, ?s), TimeRelatedError_end_at(?c, ?e), error_at(?d, ?b), lessThan(?b, ?e) -> in_range(?d, true)
It works because everything after greaterThan will only be called if the statement (greaterThan) is true, in the end if the end is also less than, we can call it in_range. I leave it here, for other that stumble upon the same question.

Python: Why my function returns None and then executes

So, I have a function which basically does this:
import os
import json
import requests
from openpyxl import load_workbook
def function(data):
statuslist = []
for i in range(len(data[0])):
result = performOperation(data[0][i])
if result in satisfying_results:
print("its okay")
statuslist.append("Pass")
else:
print("absolutely not okay")
statuslist.append("Fail" + result)
return statuslist
Then, I invoke the function like this (I've added error handling to check what will happen after stumbling upon the reason for me asking this question), and was actually amazed by the results, as the function returns None, and then executes:
statuslist = function(data)
print(statuslist)
try:
for i in range(len(statuslist)):
anotherFunction(i)
print("Confirmation that it is working")
except TypeError:
print("This is utterly nonsense I think")
The output of the program is then as follows:
None
This is utterly nonsense I think
its okay
its okay
its okay
absolutely not okay
its okay
There is only single return statement at the end of the function, the function is not recursive, its pretty straightforward and top-down(but parses a lot of data in the meantime).
From the output log, it appears that the function first returns None, and then is properly executed. I am puzzled, and I were unable to find any similar problems over the internet (maybe I phrase the question incorrectly).
Even if there were some inconsistency in the code, I'd still expect it to return [] instead.
After changing the initial list to statuslist = ["WTF"], the return is [].
To rule out the fact that I have modified the list in some other functions performed in the function(data), I have changed the name of the initial list several times - the results are consistently beyond my comprehension
I will be very grateful on tips in debugging the issue. Why does the function return the value first, and is executed after?
While being unable to write the code which would at the same time present what happened in my code in full spectrum, be readable, and wouldn't interfere with no security policies of the company, I have re-wrote it in a simpler form (the original code has been written while I had 3 months of programming experience), and the issue does not reproduce anymore. I guess there had be some level of nesting of functions that I have misinterpreted, and this re-written code, doing pretty much the same, correctly returns me the expected list.
Thank you everyone for your time and suggestions.
So, the answer appears to be: You do not understand your own code, make it simpler.

"Re-declared Defined Without Usage" One Script but Not The Other?

This sounds like it should be blindingly obvious but there's something quirky going on.
So I have two scripts. Largely the same but a few variances here and there. They both run big loops and they both use global variables. Yes, I know this is bad. Tidying it up is on my to do list but I'm on a time constraint at the moment.
One script works fine. As expected.
The other works fine... for the most part. Then it bugs out once it iterates through the loop again. It's very strange because the code has very little differences but I did pick up on something which I can't explain.
The variable I use to track my position in the loop is set like this in script 1 (which works flawlessly):
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
The second script has:
global CurrentMatchScan
while True:
print "=Starting Loop="
Loopcounter = 0
CurrentMatchScan = -1
LoadMatch()
However in the second script PyCharm highlights the = -1 part as
Redclared'CurrentMatchScan' defined above without usage
So the obvious assumption is something further up in the code is using it. I do call a function later on which is placed up there...
def LoadMatch():
nextbox1 = LinkList[CurrentMatchScan + 1]
nextbox2 = LinkList[CurrentMatchScan + 2]
But this is only called once CurrentMatchScan is set... and the first script has the exact same code.
Is my IDE just not noticing it on the other script or something? There's a pretty big issue with the looping on the second one and this is the only difference I can see between the two.
I know this doesn't look like a lot to go on but there's not much else to it that I can see. It's barely actually referenced.
I'd really appreciate anyone who can point out how much of an idiot I'm being and missing something really simple.
/edit:
Based on the fact that it does use CurrentMatchScan and calls LoadMatch() for the first iterations properly I'm starting to doubt this is anything but PyCharm trying to warn me I'm potentially doing something silly.
I think if this was the issue it wouldn't work at all so the warning might be a bit of a red herring when it comes to the issue I'm actually facing.

Why can't I get the output in Python?

def travel():
travel.s=0
travel.frate=[]
travel.tr=[]
def accomodation():
print"""specialises
1.place 1
a.hotel 1
b.hotel 2
Hotel1:ac/non ac rooms
Ac.for ac...
Noac.for non ac...."""
hd=[5000,6000]
hg=[4000,7000]
TAc=[1000]
Nac=[400]
ch5=input("Enter your choice")
fav=raw_input("ENter hotel choice")
mode=raw_input("Enter ac/no ac")
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
else:
frate=hd[i]+Nac
if(ch5==2):
for i in range(0,2,1):
frate=hg[i]+TAc
else:
frate=hg[i]+Nac
accomodation()
travel()
When i run the program , i get the error as List Index out of range.but in hd and hg list,there are only two elements, so index number will be from 0 right?? Is there anything i should import?? I even gave statements like this:
travel.frate=travel.hg[i]+TAc
but it still doesn't come.Thank you for your effort.
the indentation is proper now,but the output is still not coming.
The specific issue you are encountering is caused by these lines here:
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
hd[i] looks at hd[5000] and hd[6000] which will throw an IndexError.
But if you fix that, you're going to run into another error, because
frate=hd[i]+TAc
tries to add a list TAc to an integer hd[i], which is an unsupported operation. You probably need frate=hd[i]+TAc[0], or even better, make TAc a number rather than a list. This issue occurs elsewhere in your code as well.
Finally, while not causing explicit issues in your code right now, there are two other problems:
ch5=input("Enter your choice") is dangerous since input tells Python to run whatever code snippet the user enters. In this case, much safer to do ch5=int(raw_input("Enter your choice"))
for i in range(0,2,1): is really for i in range(2): - only use the starting index and jump parameters if you need to change them from their default, namely 0 and 1.
There are other issues like variable scope (you're expecting travel.frate to be modified from within accommodation, but that's not happening) and defining variables in functions like travel.frate (not invalid syntax, but definitely strange) but those are probably better addressed outside of this question.

Clear and exit_fullscreen seem not to work

I've started to play around with blessings - so far I'm liking it a lot since it does make things a lot easier.
However I tried to clear the screen without success... enter_fullscreen seems to work tho since that "clears" it - but exit_fullscreen doesn't bring me back to the original view.
term = blessings.Terminal()
term.enter_fullscreen
with term.location():
print(term.move(0,(term.width/2)-7) + term.bold_green("Test Test Test"))
print(term.move(5,(term.width/2)-7) + term.bold_red("Test Test Test"))
time.sleep(5)
term.clear
term.exit_fullscreen
This works except for clear and exit_fullscreen it seems. There is no error message or anything, it just doesn't seem to do anything.
Does anyone know how it works?
Edit: Neither
term.clear
nor
term.clear()
seem to work...
edit2:
I can pretty much do this and the result is the same as above. It does the coloring and placement but not clearing or anything else.
term = blessings.Terminal()
with term.location():
print(term.move(0,(term.width/2)-7) + term.bold_green("Test Test Test"))
print(term.move(5,(term.width/2)-7) + term.bold_red("Test Test Test"))
Just as with all the other capabilities exposed by Blessings, you have to print them for them to have any effect. What's happening under the covers is that your terminal emulator is "listening" for certain sequences, and then it responds by taking actions such as switching in or out of fullscreen mode. So, in your case, saying print term.enter_fullscreen should do the trick. Let me know if you have any more problems!
As I read through your issue (facing the same one myself) I realized that I had forgotten that all the term.some_formatting() calls returned a value that you then had to print. The clear function merely returns the appropriate escape sequences.
If you add:
print(term.clear())
when you want it cleared it should work.
Additionally, I had issues with ex_fullscreen, so I used the wrapper style call of fullscreen:
with term.fullscreen():
a_function_or_some_code()
That should return you to your previous state upon exiting the code block.

Categories

Resources