Python Output Numbers: Display, Calculate and Format Numbers in Python
Numbers are an important part of almost every programming application. Whether you are developing a calculator, processing student marks, calculating business revenue, or analyzing network performance, your Python programs will frequently work with numerical values.
Python provides built-in functionality to display numbers, perform mathematical operations, combine calculations, and format numerical results.
The print() function can display integers, floating-point values, and the results of mathematical expressions.
In this tutorial, you will learn how to display numbers in Python, perform calculations, work with different numerical types, and format numerical output with practical examples.
1. Displaying Numbers Using the print() Function
Python allows you to display numerical values directly using the print() function.
Unlike text, numerical values do not need quotation marks.
Example 1: Display an Integer
print(100)
Output:
100
Here, 100 is an integer value.
Example 2: Display a Floating-Point Number
print(25.75)
Output:
25.75
The value 25.75 is a floating-point number because it contains a decimal component.
Example 3: Display Multiple Numbers
print(10, 20, 30, 40, 50)
Output:
10 20 30 40 50
Python displays the numbers with spaces between them by default.
2. Understanding Integer and Floating-Point Numbers
Python supports different numerical data types.
Two commonly used types are:
Integer (int):
Represents whole numbers without a fractional component.
Examples:
print(10)
print(250)
print(-75)
Output:
10
250
-75
Floating-Point (float):
Represents numbers that include a fractional component.
Examples:
print(10.5)
print(99.99)
print(-25.75)
Output:
10.5
99.99
-25.75
Checking the Data Type of a Number
Python provides the built-in type() function to identify the type of a value.
number1 = 100
number2 = 25.75
print(type(number1))
print(type(number2))
Output:
<class 'int'>
<class 'float'>
The first variable contains an integer, while the second contains a floating-point number.
3. Displaying Numbers Stored in Variables
In practical applications, numerical values are usually stored in variables before being processed.
Example
age = 25
salary = 35000
percentage = 87.5
print(age)
print(salary)
print(percentage)
Output:
25
35000
87.5
Python displays the values stored in the variables.
Example: Displaying Student Marks
student_name = "Rahul"
math_marks = 85
science_marks = 90
english_marks = 80
print("Student:", student_name)
print("Math Marks:", math_marks)
print("Science Marks:", science_marks)
print("English Marks:", english_marks)
Output:
Student: Rahul
Math Marks: 85
Science Marks: 90
English Marks: 80
This example combines text and numerical values in the same output.
4. Performing Mathematical Operations and Displaying Results
Python supports several arithmetic operators that can be used to perform calculations.
Let's understand these operations through examples.
Example 1: Addition
number1 = 100
number2 = 50
result = number1 + number2
print("Addition:", result)
Output:
Addition: 150
The + operator adds the two numbers.
Example 2: Subtraction
price = 500
discount = 100
final_price = price - discount
print("Final Price:", final_price)
Output:
Final Price: 400
The - operator subtracts the discount from the original price.
Example 3: Multiplication
quantity = 5
price_per_item = 200
total = quantity * price_per_item
print("Total Amount:", total)
Output:
Total Amount: 1000
The * operator multiplies the quantity by the price.
Example 4: Division
total_marks = 450
subjects = 5
average = total_marks / subjects
print("Average Marks:", average)
Output:
Average Marks: 90.0
The / operator performs division and returns a floating-point result.
Example 5: Floor Division
Floor division returns the quotient rounded down to the nearest integer for integer operands.
result = 17 // 5
print(result)
Output:
3
Because 17 divided by 5 is 3.4, floor division produces 3.
Example 6: Modulus
The modulus operator % returns the remainder after division.
result = 17 % 5
print(result)
Output:
2
When 17 is divided by 5, the remainder is 2.
Example 7: Exponentiation
The ** operator raises one number to the power of another.
result = 2 ** 4
print(result)
Output:
16
This represents:
2 × 2 × 2 × 2 = 16.
5. Displaying the Result of Multiple Calculations
Python can evaluate mathematical expressions directly inside the print() function.
Example
print(100 + 50)
print(100 - 50)
print(100 * 5)
print(100 / 4)
Output:
150
50
500
25.0
You do not need to assign each result to a separate variable if you only want to display the result.
However, using variables is generally better when the calculated values need to be reused.
6. Combining Text and Numbers in Output
Python provides different approaches to display text and numerical values together.
Method 1: Using Multiple Arguments
age = 25
print("My age is", age)
Output:
My age is 25
Python automatically separates the arguments with a space.
Method 2: Using str()
You can convert a number into a string using the str() function.
salary = 45000
print("Monthly Salary: " + str(salary))
Output:
Monthly Salary: 45000
Method 3: Using f-Strings
F-strings provide a convenient way to insert numerical values into text.
product = "Laptop"
price = 55000
print(f"The price of {product} is Rs. {price}")
Output:
The price of Laptop is Rs. 55000
For most modern Python applications, f-strings are an excellent choice for readable output formatting.
7. Formatting Decimal Numbers
Sometimes a program produces a floating-point result with many decimal places.
For example:
result = 10 / 3
print(result)
Output:
3.3333333333333335
Displaying all decimal places may not be necessary.
Python supports formatting to control the number of decimal places.
Example 1: Display Two Decimal Places
result = 10 / 3
print(f"{result:.2f}")
Output:
3.33
The formatting expression .2f displays the value with two digits after the decimal point.
Example 2: Display Three Decimal Places
result = 10 / 3
print(f"{result:.3f}")
Output:
3.333
Example 3: Display a Percentage
score = 0.875
print(f"Percentage: {score:.1%}")
Output:
Percentage: 87.5%
The % format type converts the value into a percentage representation by multiplying it by 100 and adding the percentage symbol.
8. Formatting Large Numbers With Separators
When displaying large numerical values, separators can improve readability.
Python's format specification supports thousands separators.
Example
revenue = 2500000
print(f"Revenue: {revenue:,}")
Output:
Revenue: 2,500,000
You can also combine separators with decimal formatting.
amount = 1256789.456
print(f"Amount: {amount:,.2f}")
Output:
Amount: 1,256,789.46
This is useful for financial reports, sales summaries, and business dashboards.
9. Taking Numerical Input From Users
Python allows users to enter numerical values through the input() function.
However, input() returns the entered information as a string.
You need to convert the value into an appropriate numerical type before performing arithmetic.
Example 1: Accept an Integer
age = int(input("Enter your age: "))
print("Your age is:", age)
Example interaction:
Enter your age: 25
Your age is: 25
The int() function converts the entered text into an integer.
Example 2: Accept a Floating-Point Number
price = float(input("Enter product price: "))
print("Product Price:", price)
Example interaction:
Enter product price: 125.50
Product Price: 125.5
The float() function converts the entered text into a floating-point number.
Example 3: Add Two Numbers Entered by a User
number1 = int(input("Enter first number: "))
number2 = int(input("Enter second number: "))
total = number1 + number2
print("Total:", total)
Example interaction:
Enter first number: 100
Enter second number: 250
Total: 350
This program accepts two numbers, adds them, and displays the result.
10. Practical Example: Calculate Student Percentage
Let's develop a simple program that calculates a student's total marks and percentage.
Assume the student has five subjects, each carrying a maximum of 100 marks.
student_name = "Rahul"
maths = 85
science = 90
english = 80
computer = 95
physics = 88
total = maths + science + english + computer + physics
maximum_marks = 500
percentage = (total / maximum_marks) * 100
print("STUDENT RESULT")
print("----------------------")
print(f"Student Name: {student_name}")
print(f"Total Marks: {total}")
print(f"Maximum Marks: {maximum_marks}")
print(f"Percentage: {percentage:.2f}%")
Output:
STUDENT RESULT
----------------------
Student Name: Rahul
Total Marks: 438
Maximum Marks: 500
Percentage: 87.60%
Understanding the Calculation
Step 1: Store subject marks
Each subject's marks are stored in a separate variable.
Step 2: Calculate total marks
The + operator adds all five subject scores.
Step 3: Define maximum marks
Each subject carries 100 marks, so the maximum possible score is 500.
Step 4: Calculate percentage
The formula is:
Percentage = (Total Marks / Maximum Marks) × 100
Step 5: Display the result
The f-string displays the student's information and formats the percentage to two decimal places.
This example demonstrates how Python numerical output can be used in a practical application.
11. Common Errors When Working With Numerical Output
Error 1: Adding a String and an Integer
Incorrect:
# number = 100
# print("Total: " + number)
This causes a TypeError because Python does not allow direct concatenation of a string and an integer.
Correct:
number = 100
print("Total:", number)
Alternatively:
print(f"Total: {number}")
Error 2: Dividing by Zero
Consider:
# result = 100 / 0
# print(result)
This raises a ZeroDivisionError.
A safer approach is:
number1 = 100
number2 = 0
if number2 != 0:
print(number1 / number2)
else:
print("Division by zero is not allowed.")
Output:
Division by zero is not allowed.
Error 3: Incorrect Numerical Input
Consider:
# age = int(input("Enter age: "))
If the user enters "twenty", Python raises a ValueError because the input cannot be converted into an integer.
A basic exception-handling approach is:
try:
age = int(input("Enter age: "))
print("Age:", age)
except ValueError:
print("Please enter a valid whole number.")
This helps the program handle invalid numerical input without terminating with an unhandled exception.
12. Practice Exercises
Try the following exercises to strengthen your numerical programming skills.
Exercise 1: Display Numbers
Write a Python program to display the following numbers:
100
250
500
750
1000
Exercise 2: Addition Calculator
Create two variables, assign numerical values, calculate their sum, and display the result.
Exercise 3: Area of a Rectangle
Write a program that calculates the area of a rectangle.
Formula:
Area = Length × Width
Exercise 4: Average Marks
Create variables for five subject marks. Calculate and display the average.
Exercise 5: Percentage Calculator
Accept total marks and maximum marks from the user. Calculate and display the percentage with two decimal places.
Exercise 6: Product Billing
Create a program that accepts product price and quantity. Calculate the total amount and display the result with two decimal places.
Conclusion
Python makes numerical output and mathematical calculations straightforward through built-in functions, operators, and formatting options.
You have learned how to display integers and floating-point values, perform arithmetic operations, accept numerical input, combine text with numbers, and format decimal results.
These concepts are useful in a wide range of applications, including calculators, billing systems, student management applications, financial reports, and data analysis tools.
Continue practicing these examples to develop confidence in working with numerical values.
Next Tutorial: Explore Python Variables and Data Types to understand how Python stores, identifies, and processes different kinds of information.