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?
CodePudding user response:
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}')
CodePudding user response:
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)
CodePudding user response:
Try this:
a,b,c = 1,2,3
while True:
try:
x = input("a/b/c: ")
print(f'solution = {7 * locals()[x]}')
break
except KeyError:
print('Try again')