pythonpython-3.xcastingtypeerrorargv

How to pass a numbers list to function using command line sys.argv Python3


I want to use sys.argv[] to get a list of 5 numbers from the command line to a function (def calc_avg), so they can be averaged. But I keep getting - TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'.

import sys


def calc_avg(grades):
    average = sum(grades) / len(grades)
    return average


def get_letter(averaged_grades):
    if averaged_grades >= 90:
        return "A"
    elif averaged_grades >= 80:
        return "B"
    elif averaged_grades >= 70:
        return "C"
    elif averaged_grades >= 60:
        return "D"
    elif averaged_grades < 59:
        return "F"


def print_results(average, letter_grade):
    print(f"Average: {average}")
    print(f"Letter grade: {letter_grade}")


try:
    number_lst = int(sys.argv[1:])


except ValueError:
    print("Error, all grades must be numeric.")

calculated_average = calc_avg(number_lst)
letter_grade = get_letter(calculated_average)
print_results(calculated_average, letter_grade)

Solution

  • You can't convert a list to int, you have to build a new list converting your args one by one:

    number_lst = [int(i) for i in sys.argv[1:]]