简体   繁体   中英

Python shell showing error but cmd is running that program

I am new in python.I am doing addition of two numbers in cmd using input parameter .I am getting output on cmd but getting Error on python shell.I am using windows 7 and python shell 3.3.2 . so anyone can tell me why my code is not running on python shell ?

code:

import sys
n=int(sys.argv[1])
m=int(sys.argv[2])
print(n+m)

Error:

Traceback (most recent call last):

File "C:/pythonprogram/add.py", line 4, in

 n=int(sys.argv[1]) 

IndexError: list index out of range

sys.argv contains the command line parameters. When you run your script in the Python shell you're most likely not sending any parameters. I would suggest adding a check if there are command line arguments present like this:

import sys

if len(sys.argv) > 2:
    n=int(sys.argv[1])
    m=int(sys.argv[2])  
    print(n+m)

Check this out to find out more about Python and sys.argv

Your program is expecting two command line arguments . sys.argv is a list of command line arguments. The error IndexError: list index out of range is telling you that you tried to get list item number 2, (with index 1), but the list doesn't have that many values.

You can reproduce that error in the shell:

>> alist = ['Item 0']
>> print(alist[1])

Since alist only has item with index 0 requesting items with higher indexes will cause that error.

Now, to your exact problem. The program is telling you it expected command line arguments, but they were not provided. Provide them! Run this command:

python add.py 1 2

This will execute the script and pass 1 as the first argument, 2 as the second argument. In your case the general format is

python add.py [n] [m]

Now at that point you might be (you should be) wondering what sys.argv[0] is then, any why your n number doesn't get assigned to sys.argv[1] . sys.argv[0] is the name of the script running.

Further reading on command line arguments:

http://www.pythonforbeginners.com/system/python-sys-argv

Additional. You could modify your script to be more descriptive:

import sys
if len(sys.argv) < 3: #script name + 2 other arguments required
 print("Provide at least two numbers")
else:
 n=int(sys.argv[1])
 m=int(sys.argv[2])
 print(n+m)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM