M.G M.G - 6 months ago 8
Python Question

Python Including Existing Varible when Asking for Input

I'm trying to have a loop that a user enters names for sectors of a graph. The idea was something like this(where number of sectors was assigned a value earlier through user input).

for z in range(0, numSectors):

labels = input('Enter the label for sector',z,': ')


Is it not possible to have a variable like Z put in the argument or did I just not format it correctly somehow. If this is not possible in anyway, how would I go about achieving the same result in that case.

The question should read in the console like

Enter the label for sector 1:

Enter the label for sector 2:

Enter the label for sector 3:

...

(until the number of sectors is fulfilled)

Thanks!

Answer

Use str.format,

for z in range(1, numSectors+1):
    labels = input('Enter the label for sector {z}: '.format(z=z))

# Test result
Enter the label for sector 1: Hello
Enter the label for sector 2: World
Enter the label for sector 3: ! 

BTW, for Python2, use raw_input instead of input.

Comments