2. Basic Types: Strings
Printing
We have already seen a lot of output in the previous exercises, but this is not how Python programs would normally behave. If we were to write expressions in a Python file and run it, we would see no output at all. In order for your more complex programs to output anything you will have to use the built-in function .
A built-in function is a function that is directly built in the Python source code and thus immediately available to the programmer.
The function will likely be the built-in function you will use the most in your Python endeavor. While there are other methods to display output, the function is the most concise way to have your Python programs output anything. It is defined as follows:
Function Definition
Where the arguments can be of any Python type, such as numbers, strings or variables.
The function converts its arguments to objects and prints them on the same line separated by spaces. The function automatically forces a new line after all the arguments are printed. This is accomplished by appending the newline character to the end of the line. When no arguments are provided, only the newline character is printed. The newline character is an example of an escape sequence.
Let's take a look at some examples of function usage:
Calling with a single object as argument:
>>> print("Hello!")
|
Hello!
|
Calling with a and an object as arguments:
>>> print("The answer?", 44)
|
The answer? 44
|
Calling with a predefined variable:
>>> var = "eggs"
>>> print(var) |
eggs
|
Combining the function with the previously discussed string formatting techniques is a very useful way to preserve the readability of your code in addition to the readability of its output.
Or visit omptest.org if jou are taking an OMPT exam.