2

I want to create a python script which does various things with 6 inputs the user gives.

Short of typing,

x1=input("Enter data1")

...

x6=input("Enter data6")

is there anyway to define these variables via some sort of index? I don't know what the code would be, but it would have the effect of the following:

Let i range from 1 to 6. Let x_i=input("Enter Data_i")

1 Answer 1

2

As a pythonic way you can use a dictionary for such tasks :

d={}
for i in range(1,7):
   d['x_{}'.format(i)]=input("Enter data{}  :".format(i))

Then you can get the relative values of a variable using a simple indexing.

Also you can use collections.OrderedDict to preserve the order :

>>> from collections import OrderedDict
>>> d=OrderedDict()
>>> for i in range(1,7):
...    d['x_{}'.format(i)]=input("Enter data{}  :".format(i))
... 
Enter data1  :12
Enter data2  :13
Enter data3  :14
Enter data4  :15
Enter data5  :16
Enter data6  :17
>>> 
>>> d
OrderedDict([('x_1', '12'), ('x_2', '13'), ('x_3', '14'), ('x_4', '15'), ('x_5', '16'), ('x_6', '17')])
>>> 
>>> d['x_3']
'14'
Sign up to request clarification or add additional context in comments.

1 Comment

As may be obvious, I'm new to python, but I'm left wondering why simply writing "for i in range (1,7):" and then on a new indented line "x_i=input("Enter data_i :")" doesn't work. It gets a syntax error when I run it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.