How to add two variables in Python

Published on Aug. 22, 2023, 12:16 p.m.

To add two variables in Python, you can use the + operator. Here is an example code that adds two variables and prints the result:

var1 = 10
var2 = 5
result = var1 + var2
print(result)

This will output 15, which is the result of adding var1 and var2.

If you want to add two variables entered by the user, you can use the input() function to prompt the user to enter the two variables, convert the input to integers using the int() function, and then add them. Here is an example code that does this:

var1 = int(input("Enter the first variable: "))
var2 = int(input("Enter the second variable: "))
result = var1 + var2
print(result)

This will prompt the user to enter the two variables, add var1 and var2, and print the result.

Note that the + operator can be used for concatenating strings and adding elements to lists as well. In the case of strings, it will concatenate the two strings together. For example:

str1 = 'Hello, '
str2 = 'World!'
result_str = str1 + str2
print(result_str)

This will output Hello, World!, which is the result of concatenating str1 and str2.

In the case of lists, it will add the second list to the end of the first list. For example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result_list = list1 + list2
print(result_list)

This will output [1, 2, 3, 4, 5, 6], which is the result of adding list2 to the end of list1.

Tags:

related content