In this tutorial, we're going to talk about the very useful print statement.
As you may have guessed, the print statement is used to print arbitrary text.
In the context of Code the Blocks, this can be incredibly useful for debugging.
As we go through more tutorials, you'll begin to appreciate its usefulness.
The syntax (remember, this is fancy-talk for "format") of a print statement is
print("Whatever text you want"). Note that the argument (fancy-talk for
"input") passed to the print function is enclosed in double-quotes. This is
called a "string".
A string is just a series of characters. To represent a string, you need to enclose that series of characters in quotes (either double or single). Here are a few examples of Python strings:
But what if you wanted a string to contain a single or a double quote? Well, a string enclosed in double-quotes can use single-quotes inside it just fine. The opposite is also true. So these are all valid strings in Python:
But what if you want to use double-quotes inside a string enclosed with double-quotes or vice-versa? Well, usually you should just try to avoid it. But if you can't, then you need to "escape" the character using a backslash. The following are valid strings in Python:
By "escaping" a quote character, you're telling Python to not consider that quote the beginning or end of a string, but a part of it.
That was an overview of strings. This rabbit hole goes deep and we might go on that adventure in a future lesson.
print statementsAs I mentioned earlier, you need to pass one or more strings as arguments to the
print function. In case you give the print function multiple strings,
it'll just print all of them (this will come in very handy later). To save you
time, I've pre-populated the source pane below with some print statements. Go
ahead and hit "run". See how the "Output" tab notifies you of unread lines.
Click on the output tab and see that all those strings have been printed out as
expected.
In the next tutorial, we'll see a different kind of output that is also going to be incredibly useful: error messages.
© 2024 Abhin Chhabra | Sitemap