Home > Software engineering >  TypeError: method() takes 0 positional arguments but 1 was given
TypeError: method() takes 0 positional arguments but 1 was given

Time:09-16

I wrote an input function python program, But when run that code , IDE show that, "this function need to pass argument" Even though ,I didn't declare any argument enter image description here please help me how to solve this problem , Thank you in advance

list_number = list()

def input():
 while True: 
     try:    
      number = input("Enter your number in to list  =  ")
      if number == "Quit":
          break   
      number = int(number)  
      list_number.append(number)
      print(list_number)
     except ValueError as e:
       print(e)
       

def diagram():
    display = ""
    for i in list_number:
         for j in range(i):
             display = display  "@"
         print(display)
         display = ""       

input()
diagram()

CodePudding user response:

Several errors are noticed at glance:

  • mixture of namespace

You declared list_number as a global variable, but you cannot set value to it directly insides a function. Instead, you can let the function return a value, or use global statement to temporary allow a function to set a value to a global variable temperary.

Read more on offical document, or search keyword python namespace for relative articles.

  • name collision on builtin keyword

Some special word are reserved by python and could not be used as variable or function name, input is amoung them.

BTW: The title of your question and example code layout is confusion! Follow the tour to learn how to ask a better question and improve layout, so that people can help you out.

Example code: though the test part has some bug I don't solved...

# reomve: move it to a main progress for future disign
# list_number = list()

# rename: input is a reserved name of builtins, pick another word
def myinput(*pargs):
    if pargs:
        for arg in pargs:
            try:
                yield int(arg)
            except ValueError:
                pass

    else:
        count = 0
        while True:
            # move out of `try` statement as it won't raise any exceptions
            # imply lowercase for easier string comparison
            userinput = input("Enter your number in to list: ").lower()
            if userinput in ['quit', 'q']:
                # for interactive, give user a response
                print("Quit input procedure. Preparing Diagram...")
                break
            try:
                number = int(userinput)
            except ValueError:
                # raise a error and the output will print to output by default
                # there is no need to `print` an error
                # and, for improve, you can raise a more specific message
                # and continue your program
                msg = "The program wants a number as input, please try again.\n"
                msg  = "Type `Quit` to exit input procedure."
                print(msg)
                continue
            except KeyboardInterrupt:
                msg = "You pressed Interrupt Keystroke, program exit."
                print(msg)
                return 0
            # print a message and pass the value intercepted
            count  = 1
            print("%d: number %d is added to queue." % (count, number))
            yield number


def diagram(numbers):
    # there is no need to iter a list by index
    # and I am **not** sure what you want from your origin code
    # if what you wnat is:
    #   join number with "@" sign
    # then just use the builtins str.join method

    # valid: is_list_like
    if is_list_like(numbers):
        numstr = map(str, numbers)
        ret = "@".join(numstr)
    else:
        ret = "Nothing to export."
    return ret


def is_list_like(obj):
    """fork from pandas.api.types.is_list_like,
    search c_is_list_like as keyword"""
    return (
        # equiv: `isinstance(obj, abc.Iterable)`
        hasattr(obj, "__iter__") and not isinstance(obj, type)
        # we do not count strings/unicode/bytes as list-like
        and not isinstance(obj, (str, bytes))
    )


def main(*pargs):
    # get a generator of user input
    # if passed in values, accept parameter as user input for test
    msgout = ""
    if pargs:
        # bug: test input not filtered by int() function
        list_number = list(myinput(pargs))
        print("Run builtin test module.")
    else:
        list_number = list(myinput())
    count = len(list_number)
    # process your input by whatever means you need
    if count == 1:
        msgout  = "Received %d number from user input.\n" % count
    else:
        msgout  = "Received %d numbers from user input.\n" % count
    msgout  = "The diagram is:\n%s" % diagram(list_number)
    print(msgout)


def test():
    """simulate user input"""
    userinputs = [
        ['a', 1, 5, 4, 9, 'q'],
        [999, 'Quit'],
        ['q'],
    ]
    for userinput in userinputs:
        main(*userinput)
    # test bug:
    # 1. charactor is printed as output, too


if __name__ == "__main__":
    # remove test() if you don't need it
    test()
    main()

CodePudding user response:

Well I would change your function name from input to something else because you cannot have any function named anything from base python named in your function, This is probably the reason for your error.

CodePudding user response:

Like the others said, input() is a builtin function in Python. Try this following code:

list_number = list()

def input_func():
    while True:
        try:
            number = input("Enter your number in to list  =  ")
            if number == "Quit":
                break
            number = int(number)
            list_number.append(number)
            print(list_number)
        except ValueError as e:
            print(e)

def diagram():
    display = ""
    for i in list_number:
        for j in range(i):
            display = display   "@"
        print(display)
        display = ""

input_func()
diagram()

Also, nice to note that try should be used more precisely only where the exception is expected to be thrown. You could rewrite input_func with that in mind, such as:

def input_func():
    while True:
        number = input("Enter your number in to list  =  ")
        if number == "Quit":
            break
        try:
            number = int(number)
        except ValueError as e:
            print(e)
        else:
            list_number.append(number)
            print(list_number)
  • Related