Reputation: 15573
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?
Upvotes: 2
Views: 239
Reputation: 1121486
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.
Upvotes: 5
Reputation: 798536
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".
Upvotes: 3
Reputation:
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'
Upvotes: 1