I was practising a python related problem at Hackerrank. I am a total newbie to python. The Problem was to simply write a function, which checks if a year is leap year or not according to the Gregorian calendar.
I looked in the discussions tab, where I found out the answer, I decided to not to copy up the code and instead I wrote the code after understanding it.
So I wrote it this way:
if year%4 == 0 and (year%100 != 0 or year%400 == 0):
leap = true;
When I ran the tests, It ended up with two failed tests and two timed out tests. So I checked the solution in the discussions tab again and changed my code to:
if year%4 == 0 and (year%100 != 0 or year%400 == 0):
leap = True
When I ran this code, all my test cases passed, without any errors.
Does python have only 'True' and not 'true'?
Thank you in advance. :)
True is capitalised because Python built in constants are capitalised: https://docs.python.org/3/library/constants.html
"true" would create an error, as the program will be looking for a non-existant variable called true.
The difference is that True is the keyword and true is not. The flag is case sensitive. It is always True and False, not true or false.
Truth and False are keywords meaning true and false
. Just like the keyword for null is None
. Truth is the literal truth value
Python is case sensitive and strongly typed.
'true' is not the same as 'TRUE'
Graphic example
Related
I'm learning python right now on VS and I'm learning if statements with booleans: here's my code so far:
is_toy = False
if is_toy:
print("YOU ARE A TOY")
else:
print("you're buzz lightyear!")
no matter what the terminal prints out
y
YOU ARE A TOY
when True or
y
you're buzz lightyear!
when False,
I'm not sure whether y means yes or if there's some bug or typo
As you've suggested, there's likely a typo somewhere in your code. It's coming from somewhere earlier in your code because there is no way the code snippet you shared would print y :)
I'm new to Python and started practicing and have been doing okay until I got stuck on this problem. I think the 'else' statement is the issue but I've tried many variations and can't figure it out. Any advice is most welcome to this noob. Here is a screenshot of the error and code. Thanks! https://i.stack.imgur.com/hLzrf.png
use keyword elif instead of else. else does not need any expression
Use elif instead of else because else doesn't use expressions after it and put else after the elif containing a error message or something. You cannot put something like this:
if a > b:
elif a < b:
because there is no else statement for if a and b are equal.
You are using the else statement in the wrong way, because it cannot contain a condition. If you want to add a second condition use elif instead. And use else only when you want to define a statement to execute when no other if statement was True.
if 1 == 1:
# your statement
elif 1 == 2:
# your other statement
else:
# your statement if none of the above was true
I have to edit a python file such that after every if condition, i need to add a line which says
if condition_check:
if self.debug == 1: print "COVERAGE CONDITION #8.3 True (condition_check)"
#some other code
else:
if self.debug == 1: print "COVERAGE CONDITION #8.4 False (condition_check)"
#some other code
The number 8.4(generally y.x) refer to the fact that this if condition is in function number 8(y) (the functions are just sequentially numbers, nothing special about 8) and x is xth if condition in yth function.
and of course, the line that will be added will have to be added with proper indentation. The condition_check is the condition being checked.
For example:
if (self.order_in_cb):
self.ccu_process_crossing_buffer_order()
becomes:
if (self.order_in_cb):
if self.debug == 1: print "COVERAGE CONDITION #8.2 TRUE (self.order_in_cb)"
self.ccu_process_crossing_buffer_order()
How do i achieve this?
EXTRA BACKGROUND:
I have about 1200 lines of python code with about 180 if conditions - i need to see if every if condition is hit during the execution of 47 test cases.
In other words i need to do code coverage. The complication is - i am working with cocotb stimulus for RTL verification. As a result, there is no direct way to drive the stimulus, so i dont see an easy way to use the standard coverage.py way to test coverage.
Is there a way to check the coverage so other way? I feel i am missing something.
If you truly can't use coverage.py, then I would write a helper function that used inspect.stack to find the caller, then linecache to read the line of source, and log that way. Then you only have to change if something: to if condition(something): throughout your file, which should be fairly easy.
Here's a proof of concept:
import inspect
import linecache
import re
debug = True
def condition(label, cond):
if debug:
caller = inspect.stack()[1]
line = linecache.getline(caller.filename, caller.lineno)
condcode = re.search(r"if condition\(.*?,(.*)\):", line).group(1)
print("CONDITION {}: {}".format(label, condcode))
return cond
x = 1
y = 1
if condition(1.1, x + y == 2):
print("it's two!")
This prints:
CONDITION 1.1: x + y == 2
it's two!
I have about 1200 lines of python code with about 180 if conditions - i need to see if every if condition is hit during the execution of 47 test cases. In other words i need to do code coverage. The complication is - i am working with cocotb stimulus for RTL verification.
Cocotb has support for coverage built in (docs)
export COVERAGE=1
# run cocotb however you currently invoke it
I am getting "Knob already attached to a node" when i try to add a knob
i get this when i try to run my code from menu.py button.. if i run the script from the script editor i don't get the error.. why is that?
for i in nuke.allNodes():
if not i.knob("tempMb"):
if sum0 == 0:
nuke.message("first tmp knob created")
i.addKnob(t)
elif sum0 != 0:
nuke.message("second tmp knob created")
else:
nuke.message("no nob created")
Even though i check if there is a knob named tempMb .. it still executes it as if there was not, when there is..
edit: "t" is earlier defined as Int_Knob...
Thanks!
Try the following solution:
import nuke
t = nuke.Int_Knob( 'tempMb', 'tempMb' )
for i in nuke.allNodes():
if not i.knob("tempMb"):
if nuke.exists("sum0"):
nuke.message("First tmp knob created")
i.addKnob(t)
else:
nuke.message("Second tmp knob created")
else:
nuke.message("No knob created")
First I'm going to change the elif to just else because your if condition is already testing the elif condition and I don't see how that would be changing while in this code.
for i in nuke.allNodes():
if not i.knob("tempMb"):
if sum0 == 0:
nuke.message("first tmp knob created")
i.addKnob(t)
else:
nuke.message("second tmp knob created")
else:
nuke.message("no nob created")
Second I'm assuming that i.knob(string) doesn't check for the existence of a knob by that name, or your code would behave more as you expected. So when I read the docs it seems like a couple of things may happen:
The nodes might or might not be knobs in the list returned. If you know you only want knobs you could filter by class type. I think that might look like nuke.allNodes(nuke.Knob).
I don't think a nuke.Knob.knob(str) is a test for its name or label. I read the docs as implying that your test should be: if i.name != "tempMb": or possibly if i.label != "tempMb" it depends on how you created t.
Moving on though, I think there may be a logical error here. If you have 2 nodes (and if you make the above changes, let's assume they're both knobs), and as you loop over all nodes the first one is the tempMb, then when you check the second one it won't be that and you'll try to add t, which I assume is named tempMb too. So that's why it looks to you as though the negative condition is always occurring.
You need to restructure in one of two ways:
Before the loop, set a false boolean, in the loop set it to true when the knob is tempMb is found; you may as well exit the loop as soon as this occurs. After the loop check the boolean to see if it's safe to add t.
I see a possible function nuke.exists(s) which tells you if you have any "item" named s.
Maybe remove the loop and write the following:
if not nuke.exists("tempMb"):
# Add your knob. I'm actually not seeing `addKnob` in the docs.
nuke.exists("Name of Knob") will check if your knob exists. Try using that in your if statement.
More details on Nuke forum.
See also Documentation on nuke.exists
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.