Home > Mobile >  Why do I get None in the output of this function?
Why do I get None in the output of this function?

Time:01-04

I was asked to write a function to arrange a given number to get its maximum number. The output is correct, but I keep getting None beside the rearranged number. I don't want a new code. I want this one fixed.

    def max(s):
        l=[]
        for i in str(s):
            l.append(int(i))
        l.sort()
        l.reverse()
        for i in l:
            print(i,end="")
    
    print(max(812309))

CodePudding user response:

The way you have set up the call to your method/function, you are actually calling print on the method itself i.e. print(max(812309)).

This is incorrect, as the way the compiler reads it is that it will attempt to print the method rather than a given input (which is the usual practice -- e.g. a string, int, etc).

Judging by your description, you want to print out your numbers after having been sorted from your method. However, your method is ALREADY doing the printing; so just call the method by itself and you'll get your expected result.

CodePudding user response:

It print's None because the function does not return anything. So instead just don't print the function output and simply call the function like so:

def max(s):
    l=[]
    for i in str(s):
        l.append(int(i))
    l.sort()
    l.reverse()
    for i in l:
        print(i,end="")

max(812309)

CodePudding user response:

Because you doesn't implement a return statement inside your function.

So the python interpreter adds a "return None" at the end of your function.

Reference read this article

  •  Tags:  
  • Related