Python Tutorial (33) – Example: summing numbers

Time: Column:Python views:202

Example: Adding Two Numbers Through User Input

The following example demonstrates how to prompt the user to input two numbers and compute their sum:

Example (Python 3.0+):

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

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

# Calculate the sum
sum = float(num1) + float(num2)

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

When executing the above code, the output will be:

Output:

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 of two numbers entered by the user. We use the built-in input() function to get user input, which returns a string, so we need to convert it to a number using the float() method.

For basic arithmetic operations, such as addition, we use the + operator. Other operators include the subtraction (-), multiplication (*), division (/), floor division (//), and modulus (%). For more information on numeric operations, refer to Python's numeric operations documentation.

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

Example (Python 3.0+):

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

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

When executing this compact version of the code, the output will be:

Output:

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