Outputting text in python with print()

by Alex
Outputting text in python with print()

The print command is the backbone of Python, because it is used to display text on the screen. It is used to print “Hello World!”, which is what programmers traditionally do when learning a new language. In this article we’ll deal with this function and look at more advanced things.

How to output text in Python 3

Outputting text in Python is very easy. All you have to do is write:

print("Output text")

But it gets a little more complicated, given that there are two popular versions of Python. This example will work with Python 3+ (the version supported today), but it is worth removing the brackets in case it is Python 2:

print "Text to output."

Outputting strings and other variables

By putting text inside quotation marks, you create a string. A string in programming is any sequence of letters or numbers. Strings can also be stored as variables. This means that a word will be used to represent a string, and it can be referenced later in the code. For example:

hello_world = "Hello world!"
print(hello_world)

This code stores the string "Hello world!" in the variable hello_world. You can use it later to output text in parentheses without the quotes. Why would you want to output this text? This can be useful in situations where the content shown could potentially change while the program is running. It is also useful for retrieving information: for example, due to input from the user.

name = input("Type your name please: ")
print("Hello " + name)

If we run this code and type “Vitya” we get:

Enter your name please: Vitya
Hi Vitya

As you can see, this code asks the user to make an input and then greets him personally. This example also demonstrates how to output text by combining it with text from a variable. It is enough to put the text in quotes and add a plus sign. Note the space. However, there is another way to separate elements – a comma is used to do this. For example:

Some output techniques

If you want a blank line after text in Python when outputting it, you use the \n character to do so..:

print("Hello\n")
print(name)
Hi
Vitya

Also note that both single and double quotes are allowed. This allows quotes to be used as part of the output:

print('He 'can' code!')

And if you want to print two types of quotes, triple quotes come in handy:

print("""I said 'Hi' and I'm still waiting for 'them' to answer me."")

That’s all you need to know about text output in Python.

To summarize briefly

To print text in python just call the print() function. For example: print("Your text").

Related Posts

LEAVE A COMMENT