Python Print
Python print() Syntax
In Python, the print()
function is used to display output on the screen. It is one of the most commonly used functions, especially for beginners learning the language. This lesson will explain how the print()
function works and how to use it properly.
Basic Syntax of print()
The syntax for the print()
function is simple:
1print(object, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
However, for beginners, you usually only need to focus on the first part:
1print(object)
Where object
can be a string, number, or any other data type you want to display.
Printing Text
To print text, you must put it inside quotation marks (either single ' '
or double " "
quotes):
1print("Hello, Devs!")
Output:
1Hello, Devs!
Printing Numbers
You can also print numbers directly without quotation marks:
1print(100)
Output:
1100
Printing Multiple Items
The print()
function allows you to print multiple items at once. Just separate the items with a comma ,
:
1print("I have", 3, "laptops")
Output:
1I have 3 laptops
By default, Python adds a space between each item you print. You can change this behavior using the sep
argument (explained below).
The sep Argument
The sep
argument in print()
allows you to change the separator between items. The default is a space, but you can use anything else, like a comma or dash:
1print("laptop", "mouse", "keyboard", sep=", ")
Output:
1laptop, mouse, keyboard
The end Argument
By default, the print()
function ends with a newline, so each print()
call outputs on a new line. You can change this behavior using the end
argument:
1print("Hello", end=" ")
2print("World!")
Output:
1Hello World!
In this example, the first print()
does not add a new line, and the second one continues on the same line because we changed end
to " "
.
Combining Strings and Variables
You can combine text and variables in a print()
statement. Use commas to separate them:
1name = "Alex"
2age = 25
3print("My name is", name, "and I am", age, "years old.")
Output:
1My name is Alex and I am 25 years old.
Escape Characters
To print special characters like quotes or new lines, use escape characters. The most common escape characters are:
\n
for a new line\t
for a tab\\
for a backslash\"
for double quotes
Example:
1print("Hello\nWorld!")
Output:
1Hello
2World!