Skip to content

Instantly share code, notes, and snippets.

@bennuttall
Created January 28, 2013 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennuttall/4652238 to your computer and use it in GitHub Desktop.
Save bennuttall/4652238 to your computer and use it in GitHub Desktop.
Code snippets from Ternary Operator & Shorthand Code blog post
if x > 0:
var += 1
var += 1 if x > 0 else 0
if (a > b) {
result = x;
}
else {
result = y;
}
var += 2*(x>0) # increment by 2 if (and only if) true
var += x*(x>0) # increment by x if (and only if) true
var += y*(x>0) # increment by y if (and only if) true
def sum_digits_greater_than_ten(n):
return sum([int(j) for j in str(n)]) > 10
def sum_digits_greater_than_ten(n):
return True if sum([int(j) for j in str(n)]) > 10 else False
result = a > b ? x : y;
<?php
echo 'User is ' . $user['loggedin'] ? 'online' : 'offline';
vowels += 'y'
print all([j in vowels for j in 'you'])
# returns True because all the values in the resultant list are True
vowels = 'aeiou'
print sum(j in vowels for j in 'stringy cheese') > 5
# returns False because the sum of the values in the resultant list is 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment