Search code examples
pythonvariable-assignmentboolean-operations

Python assignment with AND and OR


I am not much familiar with python. and I am write now looking into one code from python and it says something like this:

query = url.query and ('?' + url.query) or ''

can anyone help me understand what this means. I found something similar here. but I couldn't interpret the above statement. I am suppose to convert this line in Java.


Solution

  • That is very old - and quite unreliable - syntax for a ternary if. In modern Python it should be:

    query = '?' + url.query if url.query else ''
    

    and in Java:

    query = url.query == '' ? '' : '?' + url.query