How To Add Two Variables In Python

Adding two variables in Python is a fundamental concept and a simple operation that every beginner should learn. In this tutorial, we will demonstrate how to add two variables in Python using different data types, like integers, floating-point numbers, and strings.

Step 1: Declare and Assign variables

First, we need to declare two variables and assign values to them. For instance, let’s declare two integer variables named ‘a’ and ‘b’ and assign the values 5 and 7, respectively:

Similarly, we can declare two floating-point variables named ‘x’ and ‘y’ and assign the values 3.5 and 4.8:

Finally, let’s declare two strings named ‘str1’ and ‘str2’, and assign the values ‘Hello’ and ‘World’:

Step 2: Add variables using the + operator

Now that we have our variables, we can use the ‘+’ operator to add the values of the variables. This operator works differently for different data types.

For integers and floating-point numbers, the addition operator will perform arithmetic addition:

For strings, the addition operator will concatenate the strings:

Step 3: Display the result

After adding the variables, we can display the results using the print() function. Let’s print the sum of the integers, floating-point numbers, and the concatenated strings:

The output should be:

Sum of integers: 12
Sum of floating-point numbers: 8.3
Concatenated strings: HelloWorld

Full code:

Conclusion

In this tutorial, we learned how to add two variables in Python using integers, floating-point numbers, and strings. The process is straightforward, involving the declaration of two variables, the use of the ‘+’ operator to add them, and finally displaying the results using the print() function. This basic operation is essential for understanding more complex operations in Python.