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 numbers
1def 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 number
4print(classify(5))
# Test with a negative number
5print(classify(-3))

Output

positive
non-positive
Practice typing this code

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

More Python examples at level 3

← Python typing practice