0

So , I have this code snippet :

import sys

while True:
  print("Make sure the number of digits are exactly 12 : ")
  x = input()
  if str(x) == 12:
      break

  code = []

  for i in range(12):
      code[i] = int(x[i])

I want the program to repeat the lines , "Make sure .... 12 :" if 12 digits are not inputed. After that , I am copying them to an array to access each individual element of it to do very basic arithmetic calculations . Am I going in the right direction ? I am totally new to python , how can I fix this ? The above code is showing the following error .

Traceback (most recent call last):
  File "C:\Users\Arjo\Desktop\hw2a.py", line 14, in <module>
    code[i] = int(x[i])
IndexError: list assignment index out of range

3 Answers 3

3

You're not creating an array of inputs with x, but rather overwriting it each time. Your comparison is also wrong; you don't want to see that the string of x is, 12, but that it has a length of 12:

x = []
while True:
  print("Make sure the number of digits are exactly 12 : ")
  x.append(input())
  if len(x) == 12:
      break
Sign up to request clarification or add additional context in comments.

5 Comments

Are you sure you want to break when the length of x is 12?
@gnibbler I think so .. why?
The way the code is indented now, all of the stuff about code will be skipped
@gnibbler true, I didn't consider that; it should probably be dedented then
Depends on the intent of the while loop. If there is supposed to be just one input processed the part under the break should be dedented.
1

IndexError: list assignment index out of range is occuring because you have an empty list and are trying to update the first element. Since the list is empty there is no first element, so the exception is raised.

One way to correct this problem is to use code.append(x[i]) but there is an easier way in this case. The default list constructor will do exactly what you want

I think you probably want something like this

while True:
  print("Make sure the number of digits are exactly 12 : ")
  x = input()
  if len(x) != 12:   # if the length is not 12
      continue       # ask again

  code = list(x)

This will keep asking for more input until exactly 12 characters are entered

2 Comments

so i won't need to use the for loop part at all then ? , how should I access the individual elements in code array ? . Also , we can skip this line then code = [] ?
@novice7, you don't need the code = [] line. You access the elements as you were code[i] where i is bewteen 0 and 11
0

No, this doesn't look like it will work... Try changing this:

if str(x) == 12:
      break

into this:

if len(str(x)) == 12: 
    break

Hope that helps...

Comments

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.