0

This is my program

Why do I have keep getting index error whenever I provided less than 3 in my command line argument

This is the sample output

3
  • When you're providing less than 3 arguments in your command line, you're still trying to access sys.argv[1] and sys.argv[2] even though they aren't there. Commented Sep 8, 2020 at 16:36
  • 2
    1) You can add your source code directly to the question instead of an image. 2) With python3 fruits.py apple, you only pass 1 argument but you try to get 2nd and 3rd. If you use python3 fruits.py apple arg2 arg3, it will not raise an error. Commented Sep 8, 2020 at 16:36
  • Oww, okay I get it, how do i fix it thou?? Commented Sep 8, 2020 at 16:37

2 Answers 2

2

Because you are checking after you have assigned the values.

Try implementing an If else statement.

if (has 3 arguments):

assign values

else:

print('Missing/Many Arguments')
Sign up to request clarification or add additional context in comments.

Comments

0

It's much better to put the actual code instead of an image by the way.

You are trying to get index 2 (3rd item in the list) of a list that only has 2 items in it when you do second_arg = sys.argv[2]. Since the list is not that long, that is why it is throwing an error.

You may want to do your assignments after your if statement. That way you'll know that you can index that far.

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.