Python: Conditional Assignments

By Eric Downing. Filed in Python  |  
TOP del.icio.us digg

There are times that you may want to assign a different value to a variable based on the value of another variable. This can be accomplished in many compiled languages with the ternary operator.

In Python the syntax for this is different because python was written to allow you to read a line of code and have a better understanding of what the code is doing. Python uses conditional assignment where you can use an if statement to help decide what the variable should be assigned.

a = "Happy" if weather == "sunny" else "Sad"

So reading this code states: “a is set to “Happy” if weather equals sunny else a is “Sad”” .

Leave a Reply