[Python] Conditional/ternary operator for assignments in Python? [duplicate]

Discussão em 'Python' iniciado por Stack, Agosto 22, 2025.

  1. Stack

    Stack Membro Participativo

    Many languages have a conditional (AKA ternary) operator. This allows you to make terse choices between two values based on a condition, which makes expressions, including assignments, concise.

    My code has conditional assignments:

    if condition:
    var = something
    else:
    var = something_else


    In C it'd be:

    var = condition ? something : something_else;


    In Python, is there a trick you can use to get the assignment onto a single line to approximate the advantages of the conditional operator?

    Continue reading...

Compartilhe esta Página