For more information on concepts covered in this lesson, you can check out:
00:00 Here’s a feature introduced in version 3.8 of Python, which can simplify the function we’re currently working on. It’s called an assignment expression, and it allows you to save the return value of a function to a variable while at the same time doing something else with the return value. C and C++ programmers are very familiar with this concept, although we often do it by accident instead of on purpose. With Python’s notation, often referred to as the walrus operator, you have to be deliberate when using it, meaning you won’t make a lot of the mistakes I made when accidentally performing this type of operation.
This version of the program also takes advantage of the fact that
tryParse() will return
None for the numeric part of the return value tuple if the attempted conversion failed. You can now use this to test if the
tryParse() function worked, so you don’t even need to return the Boolean value anymore.
Just have it return a proper numeric value or
None and let the test be whether or not the value return was
None. So here, you see the script to test this new version with the same strings you’ve seen tested before.
tryParse() now only returns the numeric value, if it worked, or
None, if it didn’t. The testing script checks to see if the value returned is not
None and at same time saves that return value to the variable
If it is indeed not
None, that means it returned a value which can be used—in this case, displayed. If the return value was
None, then the value should be ignored and the program should take some corrective action or at least display an error.
02:52 By the way, there’s a way to write a script so that it won’t run when you import it into a REPL. I’ve just chosen not to add that to my code examples. You can look up Defining Main Functions in Python here on Real Python for more information on that. Anyway, since this function only returns a numeric value and not a tuple, you can use its return value in other expressions.
So I can multiply
10 by the result of parsing the string
"10", and this is even written to take advantage of the
int() function’s keyword parameter
base, so I could write a string in hexadecimal and it will be parsed correctly and used as well.
This will be
None, so the condition will be
False, and this will return the default value
1 at the end of this expression. Again, the assignment expression was introduced in Python version 3.8, so if you’re using a code base requiring an earlier version of Python, you’ll have to use the techniques you saw in the last lesson.
Become a Member to join the conversation.