# Writing Functions in Python

• Print
This chapter is from the book

## Putting in a Print Message

What if I want the function to not just return a number but to instead print out a user-friendly message such as the following:

`7.5 inches are equal to 19.05 centimeters.`

I can easily do that in Python. All I need to do is add a call to the built-in print function. Because print is a built-in function of Python, it’s one that you do not define yourself; it’s already defined for you. Here’s a sample of this function in action:

`>>>print(’My name is Brian O.’)My name is Brian O.`

Why did I place single-quotation marks around the message to be printed? I did that because this information is text, not numeric data or Python code; it indicates that the words are to be printed out exactly as shown. Here are some more examples:

`>>>print(’To be or not to be.’)To be or not to be.>>>print(’When we are born, we cry,’)When we are born, we cry,>>>print(’That we are come’    ’ to this great stage of fools.’)That we are come to this great stage of fools.`

The ability to use print pays off in a number of ways: I can intermix text—words placed in quotation marks—with variables.

`>>>x = 5>>>y = 25>>>print(’The value of’, x, ’squared is’, y)The value of 5 squared is 25`

By default, the print function inserts an extra blank space between one item and the next. Also, after a call to the print function is finished, then by default it prints a newline character, which causes the terminal to advance to the next line.

Now let’s combine the printing ability with the power to define functions.

`>>>def convert(x):    c = x * 2.54    print(x, ’inches equal’, c, ’centimeters.’)>>>convert(5)5 inches equal 12.2 centimeters.>>>convert(10)10 inches equal 25.4 centimeters.`

Do you now see why the print function is useful? I can call this built-in function from within a definition of one of my functions; that enables my functions to print nice output messages rather than just producing a number.