Python Crash Course : The Ultimate Beginner’s Course to Learning Python Programming in Under 12 Hours by Phoenix Eprogamy

Python Crash Course : The Ultimate Beginner’s Course to Learning Python Programming in Under 12 Hours by Phoenix Eprogamy

Author:Phoenix , Eprogamy [Phoenix , Eprogamy]
Language: eng
Format: epub
Published: 2020-08-09T16:00:00+00:00


Anonymous Functions

Anonymous functions are functions that are not declared in the standard way, using the “def” keyword. Instead of the def keyword, anonymous functions use the “lambda” keyword. These are used to create small one line functions. Unlike functions, anonymous functions cannot access variables outside of their own namespace, or global namespace. These functions can take any number of arguments and return exactly one value in an expression form.

Example

sum = lambda num1, num2: num1 + num2

print(sum(1,2))

print(sum(5,10))

The variable sum gets a value of an anonymous function. The do this by using the lambda keyword, followed by the parameters you want it to take separated by commas. After that, you use a “:” symbol, to separate the parameters from the expression. The value of sum then becomes the value of the expression, which in this case, is the value of num1, and num2 combined together. Now when you print sum it works exactly like a method, however by using lambda the code becomes a lot more compact. This is again, another case of programmer preference, and whether you would prefer to use an anonymous function over a normal one, since there is no difference in the way they work, other than the structure.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.