1

I am making a program that requires an input loop that reads from a previous list and uses that data in the user prompt. I can't find how to make the loop display the next list item on each loop.

I have tried different things but haven't got it to work. I have it set now as just itemName0 but want to have it go up till the loop ends (itemName1, itemName2 etc...)

Item names (itemName0,itemName2,etc...)

for x in range(itemNum):
    globals()['itemName%s' % x] =input("Enter item name: ")

#Item Values (itemValue0,itemValue1,...)
for x in range(itemNum):
    globals()['itemValue%s' % x] =float(input("Enter value for "+(itemName0)+(": ")))

I'm hoping to get to this:

Enter item name: Pants
Enter item name: Shirts
Enter item name: socks

Enter value for Pants: 
Enter value for Shirts:
Enter value for socks:

I need the loop to run for however the length of the user inputs as itemNum but update the items for the names.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
jDog
  • 11
  • 3
  • Python 3.6+ has [formatted string literals (f-strings](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals) that make most string formatting tasks easier: `'itemName%s' % x` becomes `f'itemName{x}'` – wwii May 19 '19 at 04:32
  • Just append `'itemName%s' % x` to a list and iterate over the list. – wwii May 19 '19 at 04:34
  • Related: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables – wwii May 19 '19 at 04:35

1 Answers1

2

The next line is wrong:

globals()['itemValue%s' % x] =float(input("Enter value for "+(itemName0)+(": ")))

Note, itemName0 is always the first item. This must be variable. I replaced this and works for me:

for x in range(itemNum):
    globals()['itemValue%s' % x] =float(input("Enter value for "+(globals()['itemName%s' % x])+(": ")))
alfredo
  • 524
  • 6
  • 9