2

I want to use conditions in variable assignment in Python like how I do it in C#.

myLang = lang=='en' ? 'en' : lang=='ger' ? 'de' : 'fa';

I found this question which says Python has this kind of assigments.

num1 = (20 if someBoolValue else num1)

But I can't figure it out how does it work in my case. Is it possible to do something like that in Python?

Community
  • 1
  • 1
Ghasem
  • 14,455
  • 21
  • 138
  • 171

3 Answers3

5

Yes, it is possible:

myLang = 'en' if lang == 'en' else 'de' if lang == 'ger' else 'fa'

The true and false expressions of a single conditional expression are just more expressions. You can put another conditional expression in that place.

If it makes it easier to read you can put parentheses around expressions to group them visually. Python doesn't need these, as the conditional expression has a very low operator precedence; only lambda is lower.

With parentheses it would read:

myLang = 'en' if lang == 'en' else ('de' if lang == 'ger' else 'fa')

There are better ways to map lang to a two character string however. Using a dictionary, for example:

language_mapping = {'en': 'en', 'ger': 'de'}
myLang = language_mapping.get(lang, 'fa')

would default to 'fa' unless the lang value is in the mapping, using the dict.get() method.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

The problem with doing this in code is that it's, well, hardcoded. Do it in data instead.

langmap = {
  'en': 'en',
  'ger': 'ge'
}

 ...
myLang = langmap.get(lang, 'fa')
 ...

Although German is given the abbreviation of "de" (for "deutsche"), not "ge".

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

The C# code is interpreted as:

myLang = lang=='en' ? 'en' : (lang=='ger' ? 'ge' : 'fa');

So just do the same for Python:

myLang = 'en' if lang=='en' else ('ge' if lang=='ger' else 'fa')

or without the parenthesis:

myLang = 'en' if lang=='en' else 'ge' if lang=='ger' else 'fa'