Unable to solve TypeError message in Python

后端 未结 2 1326
执笔经年
执笔经年 2021-01-26 06:48

I have been searching around to check why was it that at line 7 there was a TypeError that says that my arguments are not converted during string formatting but to avail.

相关标签:
2条回答
  • 2021-01-26 07:33

    command line arguments are of str type.

    When using % on a string, you're invoking the formatting operator, and since your string doesn't contain any %, you get this weird message.

    The fix is simple once you know that:

    if int(value) % 2 == 0:
    

    will do it

    (the please enter valid integers part doesn't work, you have to catch the ValueError in case the argument isn't an integer instead)

    Next strange errors you'll have is when you'll try to use max on the list of arguments. Wrong sorting will be used (lexicographical)

    The best way would be to convert your arglist to integers beforehand, and process that list.

    Let me propose a self-contained example which computes odd & even list and diff, using more pythonic techniques (and also more performant, ex: no need to compute the sum of your numbers at each iteration):

    import sys
    
    even, odd = [], []
    
    argument_list = ["1","10","24","15","16"]  # sys.argv[1:]
    
    integer_list = [int(x) for x in argument_list]  # let python signal the conversion errors and exit
    
    for value in integer_list:
        # ternary to select which list to append to
        (odd if value % 2 else even).append(value)
    
    total_even = sum(even)
    total_odd = sum(odd)
    count_even = len(even)  # if you need that
    count_odd = len(odd)
    
    diff = max(integer_list) - min(integer_list)
    
    0 讨论(0)
  • 2021-01-26 07:43

    sys.argv is automatically a list of strings. Typecast it using

    int(value) 
    

    when using it to use it as an integer.

    0 讨论(0)
提交回复
热议问题