Skip to content

Instantly share code, notes, and snippets.

@sudhamjayanthi
Last active September 25, 2020 14:54
Show Gist options
  • Select an option

  • Save sudhamjayanthi/628001e4c75db3def74f09687cea977e to your computer and use it in GitHub Desktop.

Select an option

Save sudhamjayanthi/628001e4c75db3def74f09687cea977e to your computer and use it in GitHub Desktop.
[PYTHON] One liner IF-ELSE statements
'''
-----------------------------------------------------
REQUIRED KNOWLEDGE TO UNDERSTAND:
1. Python Lists & indexing
2. Python if-else statements
3. In python when we cast a boolean to int
1. TRUE changes to 1 i.e int(True) --> 1
2. FALSE changes to 0 i.e int(False) --> 0
------------------------------------------------------
''' '''
------------------------------------------------------
SYNTAX FOR ONE LINE IF-ELSE STATEMENT IN PYTHON:
variable = [value if true, value if false][ condition ]
------------------------------------------------------
'''
------------------------------------------------------
# EXAMPLE:
x = ["1 is less than 2","1 is greater than two"][1>2]
'''
------------------------------------------------------
EXPLANATION:
Here 1 > 2 returns True and as it is given as a index of list, True gets casted to 1 [ int(True) --> 1 ]
So x will be assigned the value of second item/first index of the list.
------------------------------------------------------
'''
@sudhamjayanthi
Copy link
Author

sudhamjayanthi commented Jun 20, 2020

READ THIS ⬇️

STAR ⭐ THIS GIST if you don't know this trick. That would let me know that I was helpful to someone & would inspire me to post more gists.
- Sudham Jayanthi
Instagram
Github
Email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment