Johannes
Johannes

Reputation: 1064

Set python variable conditionally

I'd like to set a variable based on an other variable. In my case var1 can be "mean", "sum" or "max" (input parsed from a gui). Based on these strings I want to set (conditionally) another variable; like: if var1 is "mean" then var2 = 2, if var1 = "sum" then var2=4, if var1 = "max" then var2 = 6.

What is the best way to do that (for a beginner)? If I use it in a if else procedure I need to make the variables global to use them also outside the if? Is there a recommended procedure?

Upvotes: 0

Views: 440

Answers (3)

Emmanuel
Emmanuel

Reputation: 14209

Since python does not have a builtin switch-case statement, a pythonic way to do that is to use a dict:

>>> d = {'mean': 2, 'sum': 4, 'max': 6}
>>> var1 = "max"
>>> var2 = d[var1]
>>> var2
6

You no longer need to think about the scope of the variable (eventhough it's a good question to think about it !).

Upvotes: 2

Christian Witts
Christian Witts

Reputation: 11585

How about using dictionaries ?

mapping = {'mean': 2
         , 'sum' : 4
         , 'max' : 6
          }
var1 = 'mean'
var2 = mapping[var1]
# or
var2 = mapping.get(var1) # To avoid KeyErrors

Upvotes: 2

eumiro
eumiro

Reputation: 212835

Use a dictionary:

d = {'mean': 2,
     'sum': 4,
     'max': 6}
var2 = d.get(var1)

If var1 is not contained within d, var2 will default to None. If you want another default value:

var2 = d.get(var1, 0)

Upvotes: 6

Related Questions