Possible Duplicate:
Putting a simple if-then statement on one line
I am working on a python expression and I want that expression to be compressed than using the if else statement.
s = [1, 2, 3, 4]
if len(s)>5:
print s.index(5)
else:
print 'cant print'
Is there a better way than using as if else statement?
Switch Case is a cleaner and faster alternative to if-else conditions in your code. Python does not directly support Switch Case but it does provide some very useful and efficient workarounds.
I found dict is faster than if-else. This means when I want to write a switch-statement, dict is better solution.
Difference between if and if elif else Python will evaluate all three if statements to determine if they are true. Once a condition in the if elif else statement is true, Python stop evaluating the other conditions. Because of this, if elif else is faster than three if statements.
You can do:
s = [1, 2, 3, 4]
print 'y' if len(s) > 5 else 'n'
However I don't think this makes the code more readable (at a glance). Also note that if
and else
don't create a loop, they are simply statements for control flow. Loops are written using for
and while
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With