Easy Tutorial
❮ Python Func Number Choice Python Os Major ❯

Python Number Sum

Python3 Examples

The following example demonstrates how to calculate the sum of two numbers entered by the user:

Example (Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

# User input numbers
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')

# Sum calculation
sum = float(num1) + float(num2)

# Display the result
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

Execution of the above code outputs:

Enter the first number: 1.5
Enter the second number: 2.5
The sum of 1.5 and 2.5 is 4.0

In this example, we calculate the sum by taking two numbers from user input. We use the built-in function input() to get user input, which returns a string. Therefore, we need to convert the string to a number using the float() method.

For the sum operation, we use the addition operator (+). Besides addition, other operators include subtraction (-), multiplication (*), division (/), floor division (//), and modulus (%). For more numeric operations, see our Python Numeric Operations.

We can also combine the above operations into a single line of code:

Example (Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

print('The sum of the two numbers is %.1f' % (float(input('Enter the first number: ')) + float(input('Enter the second number: '))))

Execution of the above code outputs:

$ python test.py
Enter the first number: 1.5
Enter the second number: 2.5
The sum of the two numbers is 4.0

Python3 Examples

❮ Python Func Number Choice Python Os Major ❯