I'm new to stack overflow and am a noob at programming. I've stumbled across void methods; I understand what they are and what they mean/do but I feel like they don't quite click with me well, yet.
t = ['d', 'c', 'e', 'b', 'a']
t = t.sort()
This code above, for example, wouldn't work (this is from freeCodeCamp's "Python for Everybody" textbook/trinket thing).
I did Google and I know about the return and that it's probably what makes a method void. I guess I know the how but want to know why, which would probably satisfy me.
CodePudding user response:
functions in python don't return void, it's a common practice that functions which modify their inputs return None
which is a python object, note the following function.
def zero_first_lement(some_list):
some_list[0] = 0
return None
t = ['d', 'c', 'e', 'b', 'a']
t = zero_first_lement(t)
running the above function would cause t
to be None
.
python functions that have no return also return None
because they "must return something", omitting the return None
line makes no difference.
python is an interpreted language, the interpreter doesn't know what the value of t
will become from t = zero_first_lement(t)
until the function actually runs, and if the function doesn't explicitly return something then t
will be assigned None
.