I got an IndexError: list index out of range in sys.argv[1]

Question:

I want to plot this code but it entered

IndexError: list index out of range in the line: k =
float(sys.argv[1])

Can anyone help me how to fix this?

canWidth=500
canHeight=500
**strong text**
def setupWindow () :
    global win, canvas
    from tkinter import Tk, Canvas, Frame
    win = Tk()
    canvas = Canvas(win, height=canHeight, width=canWidth)
    f = Frame (win)    
    canvas.pack()
    f.pack()

def startApp () :
    global win, canvas
    import sys
    k1  = float(sys.argv[1])   # starting value of K
    k2  = float(sys.argv[2])   # ending   value of K
    x = .2                     # is somewhat arbitrary
    vrng = range(200)          # We'll do 200 horz steps
    for t in range(canWidth) :
        win.update()
        k = k1 + (k2-k1)*t/canWidth
        print ("K = %.04f" % k)
        for i in vrng :
            p = x*canHeight
            canvas.create_line(t,p,t,p+1)  # just makes a pixel dot
            x = x * (1-x) * k              # next x value
            if x <=0 or x >= 1.0 :
                print ("overflow at k", k)
                return

def main () :
    setupWindow()       # Create Canvas with Frame
    startApp()          # Start up the display  
    win.mainloop()      # Just wait for user to close graph

if __name__ == "__main__" : main()

Answers:

It looks like the program is expecting 2 float command line arguments.
`

k1  = float(sys.argv[1])   # starting value of K
k2  = float(sys.argv[2])  

`

So you shuld probably launch it with something like

python main.py 100 200

To go more into detail, your code is reading command line arguments and it’s expecting there to be 2 of them, that can also be parsed into float values.
Normally, the first command line argument is the script file itself, so sys.argv is always at least one element long.

That being said, you can either do as suggested above, and pass 2 floats as arguments, when launching the script, or just edit the script and hardcode 2 values instead of the ones read from the command line, like so

k1  = 100  
k2  = 200  
Answered By: omu_negru
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.