thestralFeather7
thestralFeather7

Reputation: 519

Basic query about python loop

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

Upvotes: 0

Views: 142

Answers (3)

John La Rooy
John La Rooy

Reputation: 304137

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

Upvotes: 1

hd1
hd1

Reputation: 34657

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...

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

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

Upvotes: 3

Related Questions