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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the more comprehensive answer. Thank you
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".

2 Comments

Thanks for the "de" thing. I edited my question. also does myLang = langmap.get(lang, 'fa') says if lang is not in langmap then lang='fa'?
@AlexJolig: myLang, but yes.
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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.