Python 3, an Illustrated Tour Transcripts
Chapter: The standard library
Lecture: Walk-through: Print Function
0:00 In this video, we're going to look at print_test.py, open it up in your editor. Let's run it and make sure that it works.
0:07 So in order to run it, I right click in PyCharm and say run print_test this just validates that it's being run with pytest, in this case it is,
0:16 it says there are 2 failures, let's look at the test here. There are 2 failures because there are 2 tests
0:22 this one here that starts with test and this function here that starts with test.
0:25 The description is this comment right here and we need to do what it says. It says print the numbers from 10 down to 0 with a space between them
0:33 and a new line at the end. And so the default behavior for the print function
0:37 puts a space between a new line at the end, so let's just try and say print nums and run that and see what happens here.
0:44 Okay, we still get 2 failures, let's see if the output from pytest helps us at all. We have an assertion, the assertion failed and said
0:54 that this string here is not equal to this string, the difference between these two strings is
1:00 that this one has a list embedded in it, and this one does not. So when we print out an object here, it just prints the __stir__ version of that
1:09 and if we want to make it so rather than the print out a list we want the individual items of the list, we need to use what's called unpacking
1:17 so we can just put a star in front of that and that should unpack them. Let's try it again, unpack the individual items from that string
1:26 and it looks like we only get one failure now, so we're good with this first one. Let's look at the assignment for the second one,
1:32 print the numbers from 10 down to 0 with a - * - between them and no new line at the end. So print, we're going to say *nums here again,
1:42 and we're going to say sep is equal to - * - and end is equal to a blank string. Let's run it and make sure that it works.
1:55 Okay, it looks like it works, let's look at the test a little bit and try and dig into what's actually going on here.
2:01 If you'll notice the import here, I'm importing stringIO this is an object that behaves as a file buffer,
2:09 and what I'm doing here is patching or monkey patching sys.stdout, I'm creating a stringIO instance, and pointing sys.stdout to it.
2:18 So when I call print down here, rather than printing out to the screen, it's printing out the string buffer
2:24 and we're pulling the value from that stream buffer out and checking the value of it. So that's how our little test is working.
2:31 Hopefully you understand a little bit about print now and again, in Python 3 print is now a function
2:37 and we can use these keyword arguments to change the behavior of the function.