2.1.1.15 Your very first program

The print() function - the keyword arguments

Python offers another mechanism for the passing of arguments, which can be helpful when you want to convince the print() function to change its behavior a bit.
We aren't going to explain it in depth right now. We plan to do this when we talk about functions. For now, we simply want to show you how it works. Feel free to use it in your own programs.
The mechanism is called keyword arguments. The name stems from the fact that the meaning of these arguments is taken not from its location (position) but from the special word (keyword) used to identify them.
The print() function has two keyword arguments that you can use for your purposes. The first of them is named end.
In the editor window you can see a very simple example of using a keyword argument.
In order to use it, it is necessary to know some rules:
  • a keyword argument consists of three elements: a keywordidentifying the argument (end here); an equal sign (=); and a valueassigned to that argument;
  • any keyword arguments have to be put after the last positional argument (this is very important)

In our example, we have made use of the end keyword argument, and set it to a string containing one space.
Run the code to see how it works.
The console should now be showing the following text:
My name is Python. Monty Python.
output
As you can see, the end keyword argument determines the characters the print() function sends to the output once it reaches the end of its positional arguments.
The default behavior reflects the situation where the end keyword argument is implicitly used in the following way: end="\n".


print("My name is", "Python.", end=" ")
print("Monty Python.")
  • Console 

Comments

Popular Posts