Conditional Expression in Python
Level 3103 keystrokes
This uses a conditional expression (ternary operator). It returns one value if the condition is true, another if false.
Python code
# Define a function that classifies numbers1def classify(n): # Conditional expression: value_if_true if condition else value_if_false # Returns "positive" if n > 0, otherwise "non-positive"2 return "positive" if n > 0 else "non-positive"3 # Test with a positive number4print(classify(5))# Test with a negative number5print(classify(-3))Output
positive non-positive
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
(× 5)× 5"× 4-× 2:× 1>× 1