Programming Questions

  • Newest
  • Popular Tags
  • Ask Question
  • Code returns None when it shouldn't
    Hello I'm still a newbie when it comes to Python, and I thought I had this challenge solved. However, whenever I run this code it returns the correct number, but it also appends None to them which then makes the result incorrect. Can anyone point out my mistake? def SecondGreatLow(arr): if len(arr) == 2: return "%s %s" % (max(arr),min(arr)) else: x = sorted(arr) y = x[1] z = x[(len(x)-1)-1] print "%s %s" % (y,z) print SecondGreatLow(raw_input())
    Boomer697 posted this question on 8/11/14 | python
  • +
  • 4
  • -
  • In else statement, You don't tell the function to return something. Printing on the screen is something like 'x = sorted(arr)', it is just a code like not a return value. So i think you should add a return value like what you did in the if statement '' return "%s %s" % (max(arr),min(arr)) ". Try to change this sensentce else: .... print "% %" % (x,z) .... to else: .... return "% %" % (x,z) I hope I helped you well
  • +
  • 1
  • -
  • Your program also needs to account for duplicate numbers in the array. You can use the set() method.
  • +
  • 0
  • -
  • On default, python functions will return a 'None' value if the function terminates without a return statement. For example, def printA(): print 'a', will print an 'a' character, and then reach the end of the function, which will return None. Therefore, doing something like this: >> a = printA() a >> a None will result in the variable (a) will be None, not the character 'a' The same logic can be applied to your code, because if the else clause is triggered (on line 5), then the function will only print (y,z) , and not return anything. So therefore, change print "% %" % (x,z) to return "% %" % (x,z) Hope I could help!
    Log in to write an answer.