Kemiance
Kemiance

Reputation: 33

Change value of a variable depending on another in python

So let's say I have two variables, var and text. I would like to know how I could change the value of text depending on what var is equal to.

For example, i receive var and it's value is "this". I would then like text to get the value 1. If var is then equal to "that", text would then be equal to 2.

I would like not to use if ... elif as there could be quite a lot of values.

Sorry for my english, I could try to re-explain if it's not clear

Upvotes: 3

Views: 2454

Answers (3)

cbo
cbo

Reputation: 96

Python has no switch/case statement. Best way to go is using a dictionary, which I find more clear even in languages providing a switch statement.

E.g.

cases = {
    'this': 'blah',
    'that': 'blub'
}

var = 'this'
text = cases.get(var, 'your default value here')
print(text)

Upvotes: 2

heemayl
heemayl

Reputation: 42127

Use a dictionary to keep the mappings:

check = { 'this': 1, 'that' : 2 }

Then you can use the value dynamically:

text = check.get(var)

Upvotes: 4

polku
polku

Reputation: 1590

Use a dict :

yourdict = {'this':1, 'that':2, ...}
text = yourdict[var]

Upvotes: 6

Related Questions