Saturday, May 23, 2020

if elif else


if elif and else


It's permitted to use an elif after another elif,  however, you cannot use any elif or else by itself in its own context. It has to be coupled with an if.

if x op y:
    print("true")
elif x op y:
    print("another")
else:
    print("done.")

where op is:    ==     !=     <     <=     >    >=

If you only have a single command associated with an if you can actually put them all on the same line, but you still need the colon : after the keyword if.

It looks something like command - if - else - command where you leave out the colons after the conditionals. Only leave out the colons when elif or else is used, i.e., a compound conditional one-liner so that it reads like English.

print("finished!") if x op y else print("not finished.")

You can also do a ternary command that would look like:

command - if - else - command - if - else - command.

The middle else-command-if triad behaves like an elif, however, you can not use the elif to shorten it because the interpreter will say "invalid syntax" error.

### note the data type is not considered; it just does the straight math
a = float(777)
b = int(777)

print("a smaller") if a < b else print("a is bigger than b") if a > b  else print("a actually equals b")

# result is
# a actually equals b
# Again we see the power of Python in that it reads just like reading the English language in a normal and natural fashion.

Be careful where you place the colons when using if, elif or else. 

Make sure you put the colons after the conditional part command on the if and elif line, and after the word else by itself.

Another thing is that if elif else must line up with the same indenting or otherwise you get an "unexpected indent" error from the interpreter. 

You can also link conditions by using the or and keywords. 

r = 88
k = 44
d = 88

if r > k and r == d:
    print("true")
else:
    print("false")


If you have a conditional that actually performs no action you need to put pass either on the same line or indented on the following line to prevent an error: "unexpected end-of-file while parsing". The elif and else can also have a pass and they all can also be on the same line (but keep the colons in this situation of using the pass keyword).


##########   this is valid code ################

r = 88
k = 44
d = 88

if r > k:
    pass # do nothing
elif d == k:
    pass # do nothing
else:
    pass # do nothing


# the display screen is blank without errors


##########   this is also valid code and is more compact ################
r = 88
k = 44
d = 88

if r > k: pass # do nothing
elif d == k: pass # do nothing
else: pass # do nothing


# the display screen is blank without errors












No comments:

Post a Comment