In Python, the language creators made a very odd - and silly - decision. Whitespace, and particularly indentation is significant.
Indentation defines where blocks of code start and stop - all data indented to the same or greater level is part of the same block.
So your code has an
if
statement that is followed by a large block of code:
else:
if (weight >=5.0):
<<< Code block starts here
print("Open Green gate.")
elif(weight >=2.0):
print("Open Red gate.")
elif(weight <= 1.0):
print("Open Yellow gate.")
<<< Code block ends here
Which means that the
elif
doesn't match up to the
if
above it, and the system has no idea what to do with it - and you get an error message.
Probably, you meant this:
weight=0.0
weight=float(input("Enter a weight in kilograms:"))
else:
if (weight >=5.0):
print("Open Green gate.")
elif(weight >=2.0):
print("Open Red gate.")
elif(weight <= 1.0):
print("Open Yellow gate.")
But you need to check all of that very carefully to be sure!
And yes, it;'s silly: because spaces and TAB characters are both whitespace - and they look the same in many, many editors but are not the same as far as Python is concerned. I can see why they did it, but ... still a very silly decision that causes a heck of a lot of problems. Whatever editor you use, make sure it has "Replace tabs with spaces" set to "ON" or it will bite you, and bite you hard!
Quote:
Hello
I don't understand why the if statement needs to match up the elif statement? can you please explain to me?
thank you
If I say to you
"Otherwise, if they have white eggs, get six"
Then you have to infer I mean you to go to the shop, and perhaps get me some eggs. But you can't really understand what to do - because the instructions aren't at all clear.
If I say:
"Go to the shop. If they have brown eggs, get a dozen. Otherwise, if they have white eggs, get six. Otherwise, get me a bar of chocolate."
Then you understand what you have to do.
Your code has to do the same, so the system can't work out that it has to go to the shop at all - and in Python indentation is the key to that.
Your code version is like this:
Go to the shop.
If they have brown eggs,
get a dozen.
Otherwise, if they have white eggs,
get six.
Otherwise,
get me a bar of chocolate.
What you need to do is use the indentation to "match up" the various parts of the code:
If they have brown eggs,
get a dozen.
Otherwise, if they have white eggs,
get six.
Otherwise,
get me a bar of chocolate.
Now the system can tell that "Otherwise, if they have white eggs, get six." is meant to work with "If they have brown eggs, get a dozen." because the two chunks of text are indented to the same level.
Does that make sense?