Loading lesson path
If you have only one statement to execute, you can put it on the same line as the if statement.
Formula
a = 5 b = 2 if a > b:print("a is greater than b")after the condition. Short Hand If ... Else If you have one statement for if and one for else, you can put them on the same line using a conditional expression:
/
else that prints a value:
a = 2 b = 330 print("A") if a > b else print("B")(sometimes known as a "ternary operator"). Assign a Value With If ... Else
/
else to choose a value and assign it to a variable:Example a = 10 b = 20 bigger = a if a > b else b print("Bigger is", bigger)variable = value_if_true if condition else value_if_falseYou can chain conditional expressions, but keep it short so it stays readable:
One line, three outcomes:
a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B")Ternary operators are particularly useful for simple assignments and return statements.Finding the maximum of two numbers:
x = 15 y = 20 max_value = x if x > y else y print("Maximum value:", max_value)username = ""
display_name = username if username else "Guest"
print("Welcome,", display_name)Shorthand if statements and ternary operators should be used when:
You want to make a quick assignment based on a condition
While shorthand if statements can make code more concise, avoid overusing them for complex conditions. For readability, use regular if-else statements when dealing with multiple lines of code or complex logic.