Functions as Values
Regular
Create a function that takes two numbers as arguments and multiplies them, returning the result.
Assignment
Rename the function.1 Verify it works as intended.
More Advanced
Create a function, which takes a variable amount of integer numbers and returns the sum of all given numbers.
(Re)write your main()
function so that it calls your new function with all arguments you call your script with.2
Since these arguments are interpreted as strings you will need to cast all arguments first.3
Now you should expect that you have some users who like to troll you and give something else than numbers as input.
When you try to cast a string that contains no numbers to int, Python will raise a ValueError
.
Catch4 that, print your own error message and end your script.
Lambda
Let’s go for writing a Lambda function. We’ll do it step by step.
First, try to rewrite your script so that the ‘calculator’ function contains only one line of code (the line with the return
statement) and all the work is done inside the return
statement, like so:
Now replace the whole inner function with a lambda expression.5
-
Declare a new variable, assign the function to it and then call just the ‘new’ function. ↩
-
The arguments your script is called with are stored in
sys.argv
(remember to import sys!). The first entry in this list is always the name of the script, so you should remove this entry somehow before moving on in the script. ↩ -
You can cast a string to int using
int()
↩ -
Catch a exception by surrounding the possible exception source with try/except:
try: bad_command() except ExceptionName: # Handling
-
lambda param_a, param_b: expression
↩