Parameters and Return Value
The use of global variables is avoided for the sake of clarity! So how do you get values into methods to process them there?
Parameters
Parameters form the interface to methods. Parameters allow the copying of values (or references) when the method is called. These copies are then processed by the method:

Object: Parameters are the interfaces to methods
1 2 3 4 5 6 7 8 9 10 11 12 |
class Invoice: def valueAddedTax(self, sum, vatPercentage): # Definition of ("formal") parameters print(sum * vatPercentage / 100) class Program: def main(self): vatPercentage = 20 # local variable: only valid in main() invoice = Invoice() invoice.valueAddedTax(50, vatPercentage) # "arguments", also called "actual" parameters program = Program() program.main() |
By calling the method
valueAddedTax() (line 9), the arguments are copied into the local variables sum and vatPercentage: 50 into the variable sum and the content of vatPercentage from main() into the local variable vatPercentage of the method valueAddedTax(). The number of parameters is arbitrary, but the order of the arguments must not be swapped.
The above example is in need of improvement. Outputs in
the logic layer or class Invoice (line 3) have to be avoided. Otherwise the class Invoice must be changed here, if e.g. the program receives a graphical user interface (GUI).
3 Layers of programming
For this reason the VAT must be written in the UI layer and NOT in the logic layer. The scope of a variable would be limited to the method valueAddedTax(). So how do you get a value back from method to the calling method?
Return value
A method can return only one value. This return value contains either the result or an error code that can be processed in the calling method.
Object: Method returns a value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Invoice: def valueAddedTax(self, sum, vatPercentage): if (vatPercentage > 100 or vatPercentage < 0): return -1 # error code = -1 indicates first error type (method is terminated) if (sum < 0): return -2 # error code = -2 indicates second possibilty of error return sum * vatPercentage / 100; class Program: def main(self): vatPercentage = 20 invoice = Invoice() vat = invoice.valueAddedTax(50, vatPercentage) # "arguments", also called "actual" parameters if (vat >= 0): print(vat) else: # error reporting print("Error") program = Program() program.main() |
In the second program example, the result is returned (bold) or, in the event of an error, an error code (bold) in class Invoice. The evaluation or output takes place in a layer above respectively in a calling method.
But even if a method returns no result, it still makes sense to use methods with return 0; for "no error", or -1, -2, -3 ... for different errors. This is the only way to test methods automatically.