Why did I get a warning "expression is assigned to nothing" in ternary?

49 views Asked by At

I have some simple age classification code in which I try to use ternary operator. It worked, but VS Code shows a yellow line underneath the code saying that "expression ... is assigned to nothing". How do I get rid of it?

age = int(input("Input your age: "))
print("Teen") if age >= 15 else print("Kids")  # here
print("End program")

enter image description here

1

There are 1 answers

0
Kurtis Rader On

It's because do_x if x else do_y is an expression. You are normally expected to capture the result of an expression. Note that using print() isn't important. Any function you call could return one or more values. Using the ternary operator in this situation is only something you should do if writing code for an "obfuscated Python" contest. Instead simply do

if age >= 15:
  print("Teen")
else:
  print("Kids")