John Muir
John Muir

Reputation: 55

Pythonic way to structure if statement for changing variable values?

As title says, what's the pythonic way to write the following code?

if x == 1:
    myvar = "a string"
elif x == 2:
    myvar = "another string"
elif x == 3:
    myvar = "yet another string"
else:
    raise Exception("arg x must be 1, 2 or 3")

It seems a bit clumsy to do the above, and for longer examples, much more time consuming and messy.

Upvotes: 0

Views: 71

Answers (2)

Sheldore
Sheldore

Reputation: 39072

In addition to @roganjosh's solution, you can also try using try and except.

dict_values = {1: "some string", 2: "another string", 3: "yet another string"}

# Using for x = 3
x = 3

try:
    print (outcome_dict[x])
except:
    print ("arg x must be 1, 2 or 3")
# yet another string

# Using for x = 4
x = 4

try:
    print (outcome_dict[x])
except:
    print ("arg x must be 1, 2 or 3")
# arg x must be 1, 2 or 3

Upvotes: 1

roganjosh
roganjosh

Reputation: 13185

You want to use a dictionary for this:

x = 3 # Then try with 4

outcome_dict = {1: "some string", 2: "another string", 3: "yet another string"}

my_var = outcome_dict.get(x)

if my_var is None:
    raise Exception("arg x must be 1, 2 or 3")

print(my_var)

The dict.get() method will return None if the key is not found. In this example, all of the outcomes need to be manually typed in outcome_dict but in practice, dictionaries are easy to create for thousands of key: value pairs in a single line of code e.g. dictionary comprehensions or just regular for loops.

Upvotes: 5

Related Questions