Returning a value from a function

Lesson Details:
June 29, 2020


I: Introduction

A: The first thing you need to know is that python is an object-oriented programming language. This means that everything in the program is an object.

II: Body

A: Returning a value from a function

There are two ways to return values from a function, the return statement and the return None statement. The difference between these two ways is that if using the return statement, then all function calls after the return statement will be ignored. So if you use the return statement, then it is best to put it at the end of the function. If you use the return None statement, then only one call to this function will be ignored. Both statements can be used multiple times, but the return None statement can only be used once per function. Here’s an example of returning None with a function call: def print_number(number): number = number + 1 print(number) print_number(5) #print number 8 return None print_number(2) #print number 2 If you try to change the value of number or use another function call after this, you will get an error message. If you don’t want any more function calls after returning, then it is best to use the return statement instead of the return None statement. Here’s an example of returning None with a function call: def print_number(number): number = number + 1 print(number) print_number(5) #print number 8 return #no more function calls after returning print_number(2) #print number 2 Even though no more function calls are made after returning, returning None still won’t work properly. Only one call will be ignored by returning None, unlike returning where all calls after returning will be ignored. Here’s an example of returning None with a function call: def print_number(number): number = number + 1 print(number) print_number(5) #print number 8 return None #no more function calls after returning print_number(2) #print number 2 If you want to ignore one call but not all calls, then it is best to use the return statement instead of the return None statement. You should also remember that using the return None statement can cause your code to have bugs, so it’s best to just avoid using it altogether.

III: Conclusion

loader
Course content