Skip to content

Instantly share code, notes, and snippets.

@golgor
Last active June 9, 2020 19:55
Show Gist options
  • Save golgor/be12034bca25676721cb9c594d0e31c4 to your computer and use it in GitHub Desktop.
Save golgor/be12034bca25676721cb9c594d0e31c4 to your computer and use it in GitHub Desktop.
Using keyword "and" and "or". Not working the same way as in many other languages.
a = 0
b = 1
# If a is "falsy" a is returned, b/a is not evaluated (i.e. no division by zero error). Otherwise b/a is returned.
print(a and b/a)
s = ""
# Returning "" if the string is "". In any other case it returns the first character in the string.
# Avoiding trying to indexing s when s does not have any characters or of None type.
print(s and s[0])
# Adding a "or" to make so it always returns empty string "" even if s = None.
s = None
print((s and s[0]) or '')
# And = If x is Falsy, return X, in any other case evaluate and return y
# Or = If x is Truthy, return X, in any other case evaluate and return y
# x if x == Falsy else y (AND)
# x if x == Truthy else y (OR)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment