When you start learning Python, one of the first things you need to learn is how to display information on the screen.
For example, you might want to display:
A welcome message.
Your name and age.
The result of a mathematical calculation.
Student marks and results.
Information generated by a Python program.
Python provides a built-in function called print() for displaying information.
The print() function is one of the simplest and most frequently used functions in Python. It helps programmers display information while testing programs, solving problems, and developing applications.
In this article, we will learn how to use print() with practical examples and their outputs.
1. What Is the print() Function in Python?
The print() function is a built-in Python function that displays information in the output area, usually the terminal or console.
Let's look at a simple example.
print("Hello, World!")
Output:
Hello, World!
In this example, Python displays the text Hello, World! on the screen.
This is a common first program for beginners learning a new programming language.
Understanding the code
printis the name of the function.Parentheses
()contain the information we want to display.Double quotation marks indicate that
Hello, World!is a string.The text inside the parentheses is displayed when the program runs.
2. Syntax of the print() Function
The general syntax of the print() function is:
print(*objects, sep=' ', end='\n')
Don't worry if this syntax looks complicated. You only need to understand a few important parts initially.
A. Objects
Objects are the values or variables you want to display.
For example:
print("Python")
print(100)
print(25.5)
Output:
Python
100
25.5
Python can display strings, integers, floating-point numbers, and other values.
B. sep
The sep parameter specifies the separator placed between multiple objects.
By default, Python uses a space.
Example:
print("Python", "Java", "C++")
Output:
Python Java C++
You can change the separator.
print("Python", "Java", "C++", sep="-")
Output:
Python-Java-C++
Another example:
print(10, 20, 30, sep=" | ")
Output:
10 | 20 | 30
The sep parameter is useful when displaying data in a particular format.
C. end
By default, print() adds a newline character after displaying its output. This means the next printed output appears on a new line.
You can change this behaviour using the end parameter.
Example:
print("Hello")
print("Python")
Output:
Hello
Python
Now let's use end.
print("Hello", end=" ")
print("Python")
Output:
Hello Python
The first print() ends with a space instead of a newline, so the second output appears on the same line.
You can also use other separators.
print("Loading", end="...")
print("Complete")
Output:
Loading...Complete
3. Printing Text and Messages
You can use print() to display any text enclosed in quotation marks.
Example 1: Display a welcome message
print("Welcome to Python Programming")
Output:
Welcome to Python Programming
Example 2: Display multiple messages
print("Welcome")
print("Learn Python")
print("Build Projects")
Output:
Welcome
Learn Python
Build Projects
Each statement displays its message on a separate line because print() adds a newline by default.
Example 3: Display a multiline message
You can use three quotation marks to create a multiline string.
print("""Welcome to Python.
Learn programming step by step.
Build your first project.""")
Output:
Welcome to Python.
Learn programming step by step.
Build your first project.
This approach is useful when you want to display several lines of text.
4. Printing Variables in Python
A variable stores a value that can be used later in a program.
You can pass a variable directly to print().
Example:
name = "Rahul"
age = 20
print(name)
print(age)
Output:
Rahul
20
Python displays the values stored in the variables.
Printing a variable with a message
You can display text and a variable in the same print() statement.
name = "Rahul"
print("My name is", name)
Output:
My name is Rahul
Notice that the text is enclosed in quotation marks, but the variable name is not.
If you write "name" instead of name, Python displays the word name rather than the variable's value.
Compare the following examples:
name = "Rahul"
print("name")
print(name)
Output:
name
Rahul
This distinction is important when learning how variables work.
5. Printing Multiple Values
The print() function can display multiple values in a single statement.
Example:
name = "Amit"
age = 19
marks = 85
print(name, age, marks)
Output:
Amit 19 85
Python separates the values with spaces by default.
You can also add descriptive text.
name = "Amit"
age = 19
marks = 85
print("Name:", name, "Age:", age, "Marks:", marks)
Output:
Name: Amit Age: 19 Marks: 85
This is useful when displaying several related values.
6. Printing Mathematical Calculations
Python can perform calculations inside the print() function.
For example:
print(10 + 20)
print(50 - 15)
print(5 * 6)
print(20 / 4)
Output:
30
35
30
5.0
Python evaluates each mathematical expression before displaying the result.
You can also use variables.
a = 10
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)
Output:
15
5
50
2.0
This feature is helpful when testing mathematical formulas and developing calculator programs.
7. Using print() with String Concatenation
String concatenation means joining two or more strings together.
In Python, the + operator can join strings.
Example:
first_name = "Rahul"
last_name = "Sharma"
print(first_name + last_name)
Output:
RahulSharma
There is no space between the names because the strings are joined directly.
To include a space, add one explicitly.
first_name = "Rahul"
last_name = "Sharma"
print(first_name + " " + last_name)
Output:
Rahul Sharma
Important point
You cannot directly concatenate a string and an integer using +.
For example:
age = 20
print("My age is " + age)
This produces a TypeError because Python cannot directly concatenate a string and an integer with the + operator.
You can solve this problem by converting the integer into a string.
age = 20
print("My age is " + str(age))
Output:
My age is 20
Another simple solution is to pass both values to print().
age = 20
print("My age is", age)
Output:
My age is 20
8. Printing Output Using f-Strings
An f-string is a convenient way to insert variable values and expressions into a string.
To create an f-string, place the letter f before the opening quotation mark and put variables or expressions inside curly braces {}.
Example:
name = "Rahul"
age = 20
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Rahul and I am 20 years old.
Python replaces {name} and {age} with their values.
Example 2: Using calculations in f-strings
a = 10
b = 20
print(f"The sum is {a + b}")
Output:
The sum is 30
Python calculates a + b and inserts the result into the output.
Example 3: Displaying student details
name = "Amit"
roll_no = 101
marks = 88.5
print(f"Student Name: {name}")
print(f"Roll Number: {roll_no}")
print(f"Marks: {marks}")
Output:
Student Name: Amit
Roll Number: 101
Marks: 88.5
Example 4: Formatting decimal values
You can use f-strings to control the number of decimal places displayed.
price = 125.6789
print(f"Price: {price:.2f}")
Output:
Price: 125.68
The format specifier .2f displays the number rounded to two decimal places.
F-strings are especially useful for producing readable output in applications involving calculations, reports, and student results.
9. Using Escape Sequences with print()
Escape sequences are special character combinations that begin with a backslash \. They help you control how text appears in the output.
Let's examine some common escape sequences.
A. Newline (\n)
The \n escape sequence moves the output to a new line.
print("Hello\nPython")
Output:
Hello
Python
B. Tab (\t)
The \t escape sequence inserts a horizontal tab.
print("Name\tAge")
print("Rahul\t20")
Output:
Name Age
Rahul 20
The exact spacing depends on how tabs are displayed in your terminal.
C. Backslash (\\)
To display a literal backslash, use \\ inside a string.
print("Python\\Programming")
Output:
Python\Programming
D. Double quotation marks (\")
You can use \" to include a double quotation mark inside a double-quoted string.
print("He said, \"Python is easy.\"")
Output:
He said, "Python is easy."
E. Single quotation marks (\')
You can use \' to include an escaped single quotation mark.
print('It\'s a Python program.')
Output:
It's a Python program.
Summary of common escape sequences
| Escape sequence | Purpose |
|---|---|
\n | Starts a new line |
\t | Inserts a horizontal tab |
\\ | Displays a backslash |
\" | Displays a double quotation mark |
\' | Displays a single quotation mark |
Understanding escape sequences helps you format output correctly.
10. Using print() to Display a Simple Student Report
Let's combine several concepts to create a basic student report.
name = "Rahul Sharma"
roll_no = 101
marks1 = 85
marks2 = 90
marks3 = 88
total = marks1 + marks2 + marks3
percentage = total / 3
print("===== STUDENT REPORT =====")
print(f"Name: {name}")
print(f"Roll Number: {roll_no}")
print(f"Subject 1 Marks: {marks1}")
print(f"Subject 2 Marks: {marks2}")
print(f"Subject 3 Marks: {marks3}")
print(f"Total Marks: {total}")
print(f"Percentage: {percentage:.2f}%")
Output:
===== STUDENT REPORT =====
Name: Rahul Sharma
Roll Number: 101
Subject 1 Marks: 85
Subject 2 Marks: 90
Subject 3 Marks: 88
Total Marks: 263
Percentage: 87.67%
Explanation
The program stores the student's information and marks in variables.
It then calculates the total marks and percentage.
Finally, print() displays the report, while f-strings make it easy to insert variable values into the output.
This is a simple example of how basic Python concepts can be combined to create a useful program.
11. Common Mistakes When Using print()
Beginners often make small mistakes while writing print() statements.
Mistake 1: Forgetting quotation marks around text
Incorrect:
print(Hello World)
Python treats Hello and World as identifiers rather than ordinary text, so the statement produces an error if those identifiers are not defined appropriately.
Correct:
print("Hello World")
Output:
Hello World
Mistake 2: Missing a closing parenthesis
Incorrect:
print("Hello Python"
Correct:
print("Hello Python")
Always ensure that parentheses and quotation marks are properly matched.
Mistake 3: Confusing a variable with a string
name = "Rahul"
print("name")
print(name)
Output:
name
Rahul
Quotation marks tell Python to display the literal text. Without quotation marks, Python uses the variable's value.
Mistake 4: Expecting print() to return the displayed text
The main purpose of print() is to display information, not to return that information as its result.
For example:
result = print("Hello")
print(result)
Output:
Hello
None
The first statement displays Hello. The print() function returns None, so the variable result stores None.
This is different from functions that return calculated values.
12. Practice Questions
Test your understanding by solving these questions.
Question 1
What will be the output?
print("Welcome to Python")
print(10 + 15)
Question 2
Predict the output:
print("Python", "Java", "C++", sep="-")
Question 3
What will this program display?
print("Hello", end=" ")
print("World")
Question 4
Find the output:
name = "Amit"
age = 21
print(f"My name is {name} and my age is {age}.")
Question 5
Write a Python program to display your name, age, and city using separate print() statements.
Question 6
Write a program that stores two numbers in variables and displays their sum, difference, product, and quotient.
Question 7
What is the purpose of the \n and \t escape sequences?
Answers
Answer 1:
Welcome to Python
25
Answer 2:
Python-Java-C++
Answer 3:
Hello World
Answer 4:
My name is Amit and my age is 21.
Answer 5:
One possible solution is:
print("Rahul")
print(20)
print("Kolkata")
Answer 6:
a = 20
b = 5
print("Sum:", a + b)
print("Difference:", a - b)
print("Product:", a * b)
print("Quotient:", a / b)
Output:
Sum: 25
Difference: 15
Product: 100
Quotient: 4.0
Answer 7:
\nmoves the output to a new line.\tinserts a horizontal tab.
Conclusion
The print() function is an essential part of Python programming. It allows you to display messages, variables, calculations, and formatted information.
In this article, we learned how to:
Display text and numbers.
Print variables and multiple values.
Perform calculations inside
print().Use the
sepandendparameters.Join strings and understand f-strings.
Format decimal values.
Use escape sequences.
Create a simple student report.
Practising these examples will help you become more comfortable writing Python programs and understanding their output.
Comments
Post a Comment