Can anyone help this beginner figure out this basic Python issue? - python

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

Related

Don't understand why I get an "Expected an indented block" error with Pyomo

I would like to use the following code from Pyomo Accessing solver status and termination conditions
results = opt.solve(instance) # Solving a model instance
instance.load(results) # Loading solution into results object
if (results.solver.status == SolverStatus.ok) and (results.solver.termination_condition == TerminationCondition.optimal):
# Do something when the solution in optimal and feasible
elif (results.solver.termination_condition == TerminationCondition.infeasible):
# Do something when model in infeasible
else:
# Something else is wrong
print “Solver Status: ”, result.solver.status
Hoever, I get an error saying Expected an indented block at the elif. When inserting an indented block, I get the error Invalid syntax. I posted a screenshot of both cases. I do not understand why I get this error? I just copied and pasted the code from the official pyomo website. Do you have any idea why I am getting this error and how I can get rid of it?
You likely need to have at least 1 line of executable code within each if or elif block. Right now, you just have a comment line.
While you are "shelling out" the program, just put the command pass in each block and see if that helps. So:
if (something >= something_else):
# do something
pass
else:
# do the other thing
pass
....
When code is laid out using whitespace like python, you need something actually in the block to show that it's there. A comment isn't enough as these are ignored.
Your code currently looks like:
if ... :
# comment where block should be
elif ... :
print "something"
The comment doesn't count as an indented block.
If you really have no code to put in there yet, you can use the no-op statement pass:
if ... :
# todo
pass
elif ... :
print "something"

Difference Between True and true

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

If statement executes when it's false

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

Is there something about the os module I'm not getting?

For the last half hour I've been trying to figure out what is wrong with this code. It should be very straight forward. I've practically copied it out of the documentation at this point. But no matter what I try I receive a syntax error.
Here's the code:
def addfiles(folder):
foldercont = [os.path.normcase(f) for f in os.listdir(folder)]
for x in foldercont:
if os.path.isfile(x) == True:
files.append(os.path.realpath(x)
if os.path.isdir(x) == True:
addfiles(os.path.realpath(x))
Whenever I run this, i receive the error
if os.path.isdir(x) == True:
^
SyntaxError: invalid syntax
However, if I write the equivlent code in the interactive interpreter it runs fine.
Can this method simply not be used in an if loop or something?
Thanks for the help. I'm getting really frustrated at this point... heh.
There's a parenthesis missing at this line:
files.append(os.path.realpath(x)
^
Python complains about the True: bit because it's expecting a statement like
(x if condition else y)
As jcomeau_ictx says, you should also leave out the == True when checking for booleans:
if x:
do_something
if not y:
do_something_else
you're missing a close parentheses on the previous line.

What does this Gtk error mean and how can I fix it?

**
Gtk:ERROR:/build/buildd/gtk+2.0-2.22.0/gtk/gtktoolbar.c:2248:logical_to_physical: assertion failed: (logical == 0)
Aborted
This is happening when I run code analogous to:
if condition:
self.insert(self.toolbutton, 0)
where self is an instance of a subclass of gtk.Toolbar. The error only occurs when condition is false.
Is there an else, or elif clause, or is it just that single if clause that, when not satisfied, causes it to bomb out?
I discovered the cause of the problem. There was a number of similar statements. The problem was due to hard coding the index. Using this form:
if condition:
self.insert(self.toolbutton, self.insert(self.toolbutton, self._n)
self._n += 1
fixes it. (self._n is originally 0).

Categories

Resources