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

$ python3 my_script.py 5 12 7 18
42

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:

def func():
    return "..."

Now replace the whole inner function with a lambda expression.5

  1. Declare a new variable, assign the function to it and then call just the ‘new’ function. 

  2. 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. 

  3. You can cast a string to int using int() 

  4. Catch a exception by surrounding the possible exception source with try/except:

    try:
        bad_command()
    except ExceptionName:
        # Handling
    

  5. lambda param_a, param_b: expression