Dynamic Outputs
- 02:22
Learn how to use the format function in Python as a tool for inserting dynamic values into static text, and enhancing code readability and presentation.
Downloads
No associated resources to download.
Transcript
Another useful tool is the format function. And the format function allows you to have static text, but insert dynamic values, which is really useful when you have a piece of code where a certain value is changing that you want to output, but you want it to be presented to the user in a consistent format. So for example, let me show you we have this print, CUSIP printing, the CUSIP number, and then the coupon for a bond. And if I hold shift and press enter to execute that cell code, then this is what I get. Alternatively, let's say that I wanted to use the format function and make that dynamic. So the way that I do that is I replace the values that I wanna make dynamic, I replace those with these curly braces, and then at the end of that text, after the the closing single apostrophe, then I'm going hit dot format, and I'm gonna open parentheses. Now I'm going to put whatever values I want to include. So here I can have my CUSIP, and then you separate it by a comma and I'll have the next value.
And just for formatting, I'm gonna input those as text. But if you wanted to, you could input them as numerical values, which might be more useful depending on the piece of code that you're writing. So I'm gonna go ahead and execute this. And you're gonna see that these values, this coupon and this CUSIP have been inserted into the text and it gives you exactly the same output. So now what's useful is I could write a piece of code that then changes these values that are inserted using the format function. So for example, I could make this variable X and I could make this variable Y, and then I can write a piece of code where the values of X and Y are changing. But even as they change it, they're presented to the user in a consistent format. So you're always getting CUSIP equals X coupon equals Y.