Luca
Luca

Reputation: 13

choose variable via input (python)

i wanna choose the variable via an input

a=1
b=2
c=3

x=input("a/b/c")

The Idea is now that the calculation is 7 times 1 and therefore the solution: 7

solution=7*a

print(solution)

But python recognizes the input as string not as a variable. How do i change that?

Upvotes: 1

Views: 626

Answers (2)

balderman
balderman

Reputation: 23815

You need to create a 'lookup table' that will map the chars to numbers.

lookup = {'a':1,'b':2,'c':3}
x=input("a/b/c: ")
value = lookup.get(x)
if value is None:
    print('invalid input')
else:
    print(f'Solution is {7 * value}')

Upvotes: 3

Leo
Leo

Reputation: 1303

You can turn a string into a variable like this.

a = 1
b = 2
c = 3

x = input("a/b/c: ")
x = locals()[x]

solution = 7 * x
print(solution)

Upvotes: 0

Related Questions