CPSC120
Fundamentals of Computer Science

Printing with Python

Printing Text

To print text to the command line in Python use the built-in function print. For example:

        print("spam, ham, and eggs")

would print the following on the command line:

        spam, ham, and eggs

The text can be surrounded in either double or single quotation marks. This can be useful if you want to print a string that contains quotation marks. For example:

        print('Mrs. Bun said, "I don't like spam!"')

would print the following on the command line:

        Mrs. Bun said, "I don't like spam!"

Escape Sequences

Each call to print function will print one line of text. It is possible to print more than one line of text by using the excape sequence "\n" for a new line. For example:

        print("My lower intestine is full\nof spam.")

would print the following on the command line:

        My lower intestine is full
        of spam.

It is also possible to insert tab characters using the escape sequence "\t". This can be useful for aligning text on multiple lines. For example:

        print("Spam:\t\t$2.60")
        print("Eggs:\t\t$2.35")
        print("Spam & eggs:\t#4.95")

would print the following on the command line:

        Spam:           $2.60
        Eggs:           $2.35
        Spam & eggs:    $4.95

Printing numbers

The print function can also be used to print numbers. For example:

        print(3)
        print(1 + 2.0)

would print the following on the command line:

        3
        3.0

Text and numbers can be mixed in print statements by separating them with commas. For example:

        print("I would like", 1, "egg.")
        print("1 + 2 =", 1 + 2)

would print the following on the command line:

        I would like 1 egg.
        1 + 2 = 3

Notice that spaces are inserted between the arguments to the print function in the above examples.