English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python date and time

Python advanced knowledge

Python reference manual

Python program adds two numbers

Python example大全

In this program, you will learn to add two numbers and use the print() function to display it.

To understand this example, you should understand the followingPython programmingTopic:

In the following program, we use arithmetic addition operator+Add two numbers.

Source code

# This program adds two numbers
num1 = 1.5
num2 = 6.3
#Two numbers are added
sum = float(num1) + float(num2)
# Display sum
print('Number {0} + {1} ={2}'.format(num1, num2, sum)

Output result

Number 1.5 + 6.3 =7.8

By changing this operator, we can subtract(-),乘(*),除(/),整除(//)or find the remainder of two numbers (%).

Code: Add two numbers provided by the user

# Store input numbers
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
# Two numbers are added
sum = float(num1) + float(num2)
#  sum
print('Number {0} + {1} = {2}'.format(num1, num2, sum)

Output result

Enter the first number: 11
Enter the second number: 120
Number 11 + 120 = 131.0

In this program, we ask the user to enter two numbers, and this program displays the sum of the two numbers entered by the user.

We use the built-in function input() for input. input() returns a string, so we use the float() function to convert it to a number.

As an alternative, we can perform this addition in a single statement without using any variables, as shown below.

print('Number %.1f' %(float(input('Enter the first number: ')) + float(input('Enter the second number: '))))

Although this program does not use variables (memory storage), it is not very readable. Some people may find it difficult to understand. It is better to write clear code. Therefore, there is always a compromise between clarity and efficiency. We need to maintain a balance.

Python example大全