0

I have a program in Python 2.7 where I'm trying to refer to some variable based on a number a user inputs. I have the following:

p1 = "foo1"
p2 = "foo2"
p3 = "foo3"
p4 = "foo4"
p5 = "foo5"
p6 = "foo6"
p7 = "foo7"
k = raw_input('Enter number')

Clearly, having if statements on k would be redundant. Is there a more elegant way for my program to, given k, refer to the variable pk? For example, if k=2, the program would find variable p2.

Kshitij Saraogi
  • 6,821
  • 8
  • 41
  • 71

3 Answers3

2

Keep the values in a list

l = ['foo1', 'foo2', 'foo3']

Then you can access them by index

print l[0]

outputs

foo1
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

I recommend using a dict:

{1: 'foo1', 2: 'foo2', ...}[k]

However if you want to use a separate variable for each value then you can use locals() or globals():

locals()['p%d' % k]

(supposing type(k) == int is True)

a_guest
  • 34,165
  • 12
  • 64
  • 118
0
lst = [ "foo1", "foo2","foo3","foo4","foo5","foo6","foo7"] #save them as list

userinput = raw_input("Enter value:") #take input from user

print(lst[userinput]) #now the number from user will be the index
# to access your said object

Lets say i inputted 3 then result i get:

foo4
Taufiq Rahman
  • 5,600
  • 2
  • 36
  • 44