Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

My python program encounters an error when trying to assign a value to an array, can someone please help me?

+6 votes
asked Apr 10, 2023 by Funtri (250 points)
My code looks like the following:

elif(cmdIn == "repeatultilineString"):

        lines = []
        currentLine = 0
        ask = True
        while(ask):
            newLine = input("Line " + str(currentLine + 1) + " value(\"end\" to finih line setup): ")
            if(newLine == "end"):
                ask = False
            else:
                lines[currentLine] = newLine
                currentLine = currentLine + 1
        times = input("Input repetition times: ")
        interval = input("Input interval(in seconds) between each repetition(0 for quickest repetition): ")
        i = 1
        while(i<float(times) + 1):
            print(str(i) + ":\n")
            j = 0
            while(j<currentLine):
                print(lines[j] + "\n")
                j = j + 1
            time.sleep(float(interval))
            i = i +1

and the output is:

C:\Terminal>>>repeatMultilineString
Line 1 value("end" to finih line setup): hello
Traceback (most recent call last):
  File "/home/main.py", line 51, in <module>
    lines[currentLine] = newLine
IndexError: list assignment index out of range

Can someone help me fix this?

1 Answer

+1 vote
answered Apr 13, 2023 by Peter Minarik (86,180 points)
selected Apr 13, 2023 by Funtri
 
Best answer

Instead of

lines[currentLine] = newLine

use

lines.append(newLine)

That should work. (I did not test as you only gave part of the code.)

commented Apr 13, 2023 by Funtri (250 points)
Thanks for your help! This worked, and I am so thankful!
commented Apr 13, 2023 by Peter Minarik (86,180 points)
I'm glad you're sorted. :)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...