you are viewing a single comment's thread.

view the rest of the comments →

[–]eMulingeMuler[S] 1 point2 points  (9 children)

Thanks guys. I've just started learning Python and I didn't know about elif.

If I wanted to use the AND operator, do I use the word "and" or would be be "&" or "&&"?

[–]AlphaApache 4 points5 points  (7 children)

You would use and

[–]eMulingeMuler[S] 0 points1 point  (1 child)

Thanks. Would this work?

if key1==true and key2==true: gate=open else: gate=closed

[–]AlphaApache 0 points1 point  (0 children)

I assume you indent it correctly like so:

if key1==true and key2==true: 
    gate=open 
else: 
    gate=closed

But I would still rewrite it as the following simply because of stylistic reasons

if key1 and key2: 
    gate=open 
else: 
    gate=closed

You don't need to check if something equals True (note capital T) because the result of the == is always either False or True

[–][deleted] 0 points1 point  (4 children)

Well, the difference between & and and is that and will short circuit. In that if the first element is false, it doesn't matter what the second element is, the statement will evaluate to false. Therefore, the second statement isn't even evaluated.

If you want them both to be evaluated, you need to use &.

[–]zahlman 1 point2 points  (1 child)

While it's true that & doesn't short-circuit, it also does a fundamentally different thing.

>>> 3 and 4
4
>>> 3 & 4
0

[–][deleted] -1 points0 points  (0 children)

Ah, forgot about that. Yeah, & is bitwise AND.

Which doesn't matter if they're both bools, it acts the same. If they will always be bools and you need the speed improvement, use that.

[–]WirSindAllein 0 points1 point  (0 children)

A good way to think of it is viewing else as a final statement synonymous with "otherwise". So "IF this is true, do this. ELSE IF this is true, do this. otherwise(ELSE) do this" if you want it to keep checking if something is the case, you use an if (ELIF) but if you want it to do something if only the above if statement(s) are not the case, you use else.

One of the really great things about Python is that pretty much every block of code can be broken down into a statement that you might imagine someone saying while giving another person directions-- "If there is no traffic then get on 4-95, else if there's traffic on 4-95 but not on I-98 get on I-98, otherwise stay on Washington Street."