Hi I am python newbie and I am working on NLP using python. I am having a error in writing if-else block in python. When I am writing only if block at that time it is workin
I don't agree entirely with the accepted answer. Yes, indention is very important in Python but to state that the if-else
has to always look like that with this formatting is a little bit overboard.
Python allows you a one-liners (even multiple) as long as you don't do anything fancy in there that requires indention in thebody of the if
, elif
or else
.
Here are some examples:
choice = 1
# if with one-liner
if choice == 1: print('This is choice 1')
# if-else with one-liners
if choice == 1: print('This is choice 1')
else: print('This is a choice other than 1')
# if-else if with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
# if-else if-else with one-liners
if choice == 1: print('This is choice 1')
elif choice == 2: print('This is choice 2')
else: print('This is a choice other than 1 and 2')
# Multiple simple statements on a single line have to be separated by a semicolumn (;) except for the last one on the line
if choice == 1: print('First statement'); print('Second statement'); print('Third statement')
Usually it is not recommended to pack too many statements on a single line because then you loose one of the big features of Python - readability of the code.
Notice also that the above examples can also easily be applied to for
and while
. You can go even further as to do some crazy nesting of one-liner if
blocks if you use the ternary conditional operator.
Here is how the operator usually looks:
flag = True
print('Flag is set to %s' % ('AWESOME' if True else 'BORING'))
What this does is basically create a simple if-else
statement. You can embed it with one of your one-liners if you need more branching (but not complex one).
Hope this clarifies the situation a bit and what is allowed and not allowed. ;)