Print In Python 3
If you are new to Python, you may be wondering how to print something in Python. The answer is simple, you can use the print() function. But what if you want to print something in a different format? For example, you want to print a list of numbers, but you want to print each number on a new line. Still, you can use the print() function but you need to use a special syntax to do this. In this, we will learn how to print in python.
- Print in python
- Print other data types
- Printing multiple values
- Print using variable
- Print format
- Print separator
- Print end
- Print file
Table of Contents
Print In Python
The print() function is used to print the output in the Python console.
print() is probably the first thing that you will use in Python when you start to learn it.
The print() function can either take direct input or it can take a variable.
The input or variable can be a string, a number, a list, a dictionary, a boolean, or even another function.
Here is an example of how to use the print() function.
Example: Python hello world
print("Hello World")
Output:
Hello World
Python print new line by default
The print() function by default creates a new line (when you use no other parameter) after the output.
This means the print() function automatically creates a new line after the output, it is same like hitting the Enter key.
print("Hello John")
print("How are you?")
Output:
Hello John How are you?
Note: So if you just want to print a new line, you can use the print() function empty.
print()
Output:
The output above is a new line.
Printing other data types
You can print other data types like numbers, lists, dictionaries, booleans, etc directly using the print() function.
Here is an example that prints all the data types and also shows their output.
# Numbers
print(1)
# Lists
print([1, 2, 3])
# Dictionaries
print({'name': 'John', 'age': 36})
# Booleans
print(True)
# None
print(None)
# Strings
print("Hello, World")
# Touple
print((1, 2, 3))
# Sets
print({1, 2, 3})
Output:
1 [1, 2, 3] {'name': 'John', 'age': 36} True None Hello, World (1, 2, 3) {1, 2, 3}
Printing multiple values
You can print multiple values using the print() function by separating them with a comma.
Example:
print(1, 2, 3)
print("one", "two", "three")
Output:
1 2 3 one two three
Print using variable
You can also use a variable to print a message or anything in the print function.
Using variables makes code clear and improves readability as well as reusability.
To use a variable in the print function, you can directly use the variable name inside the print function.
Here is an example of how to use a variable in the print function.
# Variable
message = "Hello, John"
print(message)
Output:
Hello, John
You can also create expressions with variables in the print function.
message = "Hello, John!"
print(message + " How are you?")
# The + operator is used to concatenate strings
Output:
Hello, John! How are you?
Concatenate variable in the print function
In the above example, we have used 2 string outputs in the print function and concatenated them with the + operator. But what if you want to print a number or a list in the same fashion?
Let's see an example of this.
# Number
number = 10
# occurs TypeError error
print("Number = " + number)
Output:
The above code will produce a TypeError error because we are trying to concatenate a string with a number in the print function.
We must use the str() function to convert the number to a string and then can concatenate to used in the print function.
# Number
number = 10
# Convert number to string
print("Number = " + str(number))
Output:
Number = 10
Formatted printing
In the above example, you have seen that you can't directly display any data type by stitching them together with a + operator. So how will you display or output a row of data with other injected data?
The answer is formatted printing.
Formatted printing is a way to display or output data with other data injected into it. It is done by using the % operator.
Well, it is not the only way to format your data in python. There are many other ways to format your data in python. Here is the list:
- Using % operator
- Using f-string
- Using format()
Let's see these ways of formatting data in detail.
Using % operator
The % operator is used to format the data in the print function. for example, if you want to print a number with a string, you can use the %d operator within the print function at the place of the number and put the number outside the string literals separated by a % operator.
It uses the different characters to symbolize different data types. Here is the list of the different data types:
- %d - integer
- %f - float
- %s - string
- %r - raw data
Here is an example of how to use the % operator.
# Integer
num1 = 10
print("Number = %d" % num2)
# Float
num2 = 10.5
print("Number = %f" % num2)
# String
str1 = "John"
print("Name = %s" % str1)
# Raw data
print("Raw data = %r" % str1)
Output:
Number = 10 Number = 10.5 Name = John Raw data = 'John'
Using f-string
The f-string is a visually very clear way to format the data in the print function. It is also the recommended way to format the data in the print function.
To use the f-string start your string with f and then put the data or variable name of data you want to format inside the string literal. The data or variable name of data you want to format must be inside the {} brackets.
for example, print(f"Number = {num}")
print(f"We have {12} apples")
print(f"I have {7} apples and {3} oranges")
# variable
day = 100
print(f"Today is the {day}th day of the year")
# list
list = ["John", "Mary", "Peter"]
print(f"{list[0]} is my friend, and the list is {list}.")
Output:
We have 12 apples I have 7 apples and 3 oranges Today is the 100th day of the year John is my friend, and the list is ['John', 'Mary', 'Peter'].
Using format() method
The format() is a string method in python which formats another data type in a string and returns the formatted string.
Here is an example of how to use the format() method.
print("Number = {}".format(10))
print("Number = {0}".format(10))
print("Number = {1}".format(10, 20)) # This will print the second argument
print("Number = {1} and {0}".format(10, 20))
Output:
Number = 10 Number = 10 Number = 20 Number = 20 and 10
Separators in print function
The print() function has a default separator which is space. But you can change the separator by using the sep argument.
Here is an example.
# Default separator (space)
print(8, 11, 2000)
# Change separator
print(8, 11, 2000, sep="-")
# Another different separator
print(8, 11, 2000, sep="/")
Output:
8 11 2000 8-11-2000 8/11/2000
Ending in print function
We have seen above that print() function creates a new line by default. This is because the print() function has a default ending which is a newline.
But you can change the ending by using the end argument.
Here is an example of the end argument.
# Default ending (new line)
print("Hello, ")
print("World!")
# Change ending
print("Hello, ", end="") # This will not create a new line
print("World", end="!") # This will create an ending with !
Output:
Hello, World! Hello, World!
Printing to a file
To read the data of a file in python follow the steps below:
- Open the file in the read mode by using the open() function. Example
file = open("filename.txt", "r")
- Read the data from the file by using the read() function. Example
file.read()
- Print the data using print function
- Close the file by using the close() function. Example
file.close()
Let the file be data.txt and the data be Hello, World!
# Open the file
file = open("data.txt", "r")
# Read the data from the file
data = file.read()
# print the data
print(data)
# Close the file
file.close()
Output:
Hello, World!
Conclusion
We have seen how to print data and format data in the print function. We have also seen how to use the f-string and format() method.
We have also seen how to use the sep and end arguments in the print function.
Frequently Asked Questions
-
Does print work in Python 3?
No, print is not available in Python 3. Python3 uses print() function to print data.
-
What is the difference between print and print()?
Both print and print() are the same functions that are used to print data in the python console. But the print function is used in python2 and the print() function is used in python3.
-
What is %d %s in Python?
Python uses the language C convention to format data. %d is used to format integer data and %s is used to format string data.