Search Results

Monday, November 14, 2011

Python Tips and Tricks

Hey. Here's some quick Python tips and tricks that you can use when coding. There's two that I'm going to go into detail on - conditional variable setting, and multiple equality checks.

----1. Conditional Variable Assignment----

Conditional variable setting is made so that you can set a variable if a (potentially unrelated) condition is true, and set it to another value, or host of values, if other conditions are true. It's basically a method to compress if statements down to a single line. It's pretty useful. Here's how it works.

The base if-statement example that we're going to use is this:

1:  test = 1  
2:     
3:  if test == 1:  
4:     value = 10  
5:  elif test == 2:  
6:     value = "Not One"  
7:  else:  
8:     value = None  

(Hurray for finding online source code formatters! :p) As you can see, we're performing a sequence of simple if-statements to set value. There's nothing really special here - if test is 1, value is set to 10. If test is 2, value is set to the string "Not One". If test is neither one, then value is set to None. To compress this, we follow the format:

 variable = value if condition else [condition, or default value]  

As you can see, we set the variable to a value if a condition evaluates as true. Otherwise, we either continue testing conditions, or give a default value. The else statement is necessary to work, as if there's no else statement, then variable may not be set to anything if the condition evaluates as false. So, to compress down the 7-line code block above, we follow this syntax, and end up with this:

1:  test = 1  
2:    
3:  value = 10 if test == 1 else "Not One" if test == 2 else None  

As you can see, we follow the same syntax above - we set the value to an amount if a condition evaluates as true. Otherwise, we continue to test conditions, setting value to "Not One" if the next condition test evaluates as true. Finally, if it still doesn't evaluate as true, then it defaults to the last value of None.

----2. Multiple Equality Test----

This one's a lot easier to explain. The idea is just to compress two or more if-statements into a single one. Here's an example.

1:  x = 10  
2:    
3:  if x < 100 and x > 0:  
4:     print ("x is within range")  

Here, we're checking to see if the variable x is within a certain range - below 100 and above 0. We can compress this by just checking to see if 0 less than x, which is less than 100, which they both are:

1:  x = 10  
2:    
3:  if 0 < x < 100:  
4:     print ("x is within range")  

These aren't particularly new techniques, but they're both useful to know. Welp, that's all for today. Thanks for reading, and as always, have fun!

P.S. If anyone's wondering, this is the site with the formatter. I'm not a fan of how it places the line numbers in the code block, as that kind of defeats the purpose. :p It's still pretty cool, though.

No comments:

Post a Comment