0

In Python I would like to take a numerical value input and put it into a range. The goal is to iterate a question multiple times based on the number entered in the original input. What confuses me is that the the original input value changes so I don’t know how to make the range argument value change with original Input.

Number =input(“enter a number”)

for I in range(10):
      Color=input(“enter an color”)  #this input is iterated multiple times based on the number input. I dont know how make range change it’s value.
braaterAfrikaaner
  • 1,072
  • 10
  • 20
Cbeck
  • 1
  • 2

3 Answers3

0

You want to take the number your user has entered, convert it to an int, and then use that as your input to range:

Number = input(“enter a number”)
n = int(Number)

for I in range(n):
      Color=input(“enter an color”)

You need to do the int conversion because user input is stored as a string, however range expects an int. Unfortunately if the user enters something that can't be converted to an int, the conversion will fail and your program will crash. You could handle this by testing that the conversion succeeds and notifying your user otherwise:

while(True):
    Number = input(“enter a number”)
    try:
        n = int(Number)
    except:
        print("You did not enter a valid number!")
Imran
  • 12,950
  • 8
  • 64
  • 79
0

Do you want something like this:

num = int (input(“Enter a number:”) )

for I in range(num):
      Color=input(“enter an color:”)

>>>Enter a number:4
enter a color:red
enter a color:green
enter a color:blue
enter a color:brown

This is achieved by supplying the value num to python's range function.

Say you want to test this:

num = 4
for i in range(num): #Notice num being the input of range
    print(i,)
>>>0,1,2,3

This implies that the range(num) function starts from 0 and stops at num-1.

The initial output can be changed by supplying it:

 num = 4
    for i in range(2,num): #Notice 2 and num being the initial and final endpoint respectively.
        print(i,)
    >>>2,3
Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27
0

I think you're trying to do something like this...

# assuming you're writing this in python2.7, otherwise, input() is fine
number = raw_input('enter a number: ') # allow user to input a number
for i in range(int(number)): # cast the string to an integer, and do the following the requested number of times...
    color = raw_input('enter a color: ')

Be careful with the input() function if you're using python 2.7:

What's the difference between raw_input() and input() in python3.x?

For Completeness

Others have pointed out that the original could throw an error, so why not add some safety?

number = raw_input('enter a number: ')
try:
    for i in range(int(number)):
        color = raw_input('enter a color: ')
except Exception as exc:
    print exc, "You must enter a valid integer"
burling
  • 409
  • 2
  • 5