Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting IndexError when trying to use default function arguments, if no commandline arguments are passed to script

I’m having some issues with some python logic.
Not sure if that’s possible but if it’s possible with bash I guess that’s possible in every other language.

I want to use default function argument if no commandline argument is passed to script:

#!/usr/bin/env python3

import sys

def get_file_name(filename: str = "watched_movies"):
    if sys.argv[1]:
        filename = sys.argv[1]
        return filename
    return filename
    
print(get_file_name())

My code might be wrong because I was just doing some poking around.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m getting error:

Traceback (most recent call last):
  File "/home/os/scripts/python/./movies.py", line 11, in <module>
    print(get_file_name())
  File "/home/os/scripts/python/./movies.py", line 6, in get_file_name
    if sys.argv[1]:
IndexError: list index out of range

>Solution :

Try it:

#!/usr/bin/env python3
    
import sys

def get_file_name(filename: str = "watched_movies"):
    if len(sys.argv) > 1 and sys.argv[1]:
        filename = sys.argv[1]
        return filename
    return filename 
    
print(get_file_name())

In a single line:

def get_file_name(filename: str = "watched_movies"):
    return filename if len(sys.argv) == 1 else sys.argv[1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading