0

This question was part of an assignment for a software class in college. I've long since quit but I'd really like to learn python so I'm revisiting some assignments.

I've created a simple code that will convert the number of inches given, into feet and inches. So far I've been able to have it check that the input is an integer, and is positive. The final step is being able to accept the input from either the command line or the console. Like the title says, how can I check for a command line argument and if none exists, prompt for input through the console and finish executing the script?

Here's my original code made with help from here.

try:
    total_inches = int(input('Enter a distance in inches: '))
    if total_inches > 0:
        INCHES_PER_FOOT = 12
        feet = total_inches//INCHES_PER_FOOT
        final_inches = total_inches%INCHES_PER_FOOT
        
        print(str(total_inches) + '"', 'is equivalent to', str(feet) + '\'', str(final_inches) + '"')
    else:
        print('Must be a positive integer. Try again')
except ValueError:
    print('Not a number. Try again.')

As you can see, it checks the input and executes accordingly.

I've done some searching around here and here but haven't come up with anything solid yet. The first one is about input() which I know and parsing which I'm not familiar with yet. The second one led me to this clunky looking bit of code:

from sys import argv

if len(argv) == 1:
    try:
        total_inches = int(argv[1])
        if total_inches > 0:
            INCHES_PER_FOOT = 12
            feet = total_inches//INCHES_PER_FOOT
            final_inches = total_inches%INCHES_PER_FOOT
            
            print(str(total_inches) + '"', 'is equivalent to', str(feet) + '\'', str(final_inches) + '"')
        else:
            print('Must be positive')
    except ValueError:
        print('Not a number. Try again.')
else:
    try:
        total_inches = int(input('Enter a distance in inches: '))
        if total_inches > 0:
            INCHES_PER_FOOT = 12
            feet = total_inches//INCHES_PER_FOOT
            final_inches = total_inches%INCHES_PER_FOOT
            
            print(str(total_inches) + '"', 'is equivalent to', str(feet) + '\'', str(final_inches) + '"')
        else:
            print('Must be positive')
    except ValueError:
        print('Not a number. Try again.')

When I include a command line argument it still prompts for console input but otherwise executes correctly. When I omit the command line argument and try executing the script I get:

D:\Python\2>python p2e3.py
Traceback (most recent call last):
File "D:\Python\2\p2e3.py", line 5, in
total_inches = int(argv[1])
IndexError: list index out of range

I know that that means it's missing an argument but I don't understand why it doesn't skip down to the else statement or why it still asks for console input when there's a command line argument. Not sure if my indentation is wrong or if there's another function I should be using, any help would be appreciated.

  • 1
    Yiu are reinventing the wheel. Use `argparse` and mark your srgument as required. – Marcin Orlowski Sep 28 '21 at 05:14
  • I don't know what that means :/ – MaximusCodes Sep 28 '21 at 06:31
  • 1
    `argparse` is python library that deals handles command line arguments for you. It is really feature rich so you should take a look instead of wasting the time writing own implementation. And `mark your argument as required` means that `argparse` allows you to flag any argument as `required` which means that it will take care to tell the user that unless required argument is given, "thou shall no pass". There're tons of `argparse` tutorials on-line. Go for it. – Marcin Orlowski Sep 28 '21 at 21:20
  • Ok thanks! I'll definitely research that further, I appreciate the clarification. Do you know or would you be able to tell me why my code doesn't work? I get it's not the right/best way but I'd really like to understand what the code is doing/not doing to get a full picture of my limitations. – MaximusCodes Sep 29 '21 at 19:17
  • 2
    Yes, I know where bug is, but let me give you the fishing pole, not a fish -> `print(argv)`. I believe once you see the output you will get it yourself, which shall be more satisfactory :) – Marcin Orlowski Sep 29 '21 at 19:59
  • Hint: suppose you have verified that `len(argv) == 1`. In this case, what indices do you think should be valid for `argv`? – Karl Knechtel Feb 05 '23 at 11:46

0 Answers0