Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - One line if-elif-else statement

I'm trying to condense an if-elif-else statement into one line. I tried:

a == 1 ? print "one" : a == 2 ? print "two" : print "none"

But I got a syntax-error. I have also tried:

print "one" if a == 1 else print "two" if a == 2 else print "none"

But I also got a syntax-error.

What can I do to make any of these answers better or create a working answer?

like image 378
ooransoy Avatar asked Jan 02 '14 17:01

ooransoy


1 Answers

Try:

print {1: 'one', 2: 'two'}.get(a, 'none')
like image 55
Jon Clements Avatar answered Sep 18 '22 15:09

Jon Clements