89DEVs

How to add numbers in Python?

How to add numbers in Python?

To add numbers in Python, use the + operator to add two or more numbers.

add integers

If all values are integers, the result is returned as an integer. # add integers in python a, b = 1, 2 print(a + b) In this example, the variables a and b are added and the result is printed. 1 + 2 = 3 3

add float values

If at least one value is a float value, the result is returned as a float value. Even if the result ends with zero. # add float values in python a, b = 1.5, 1.5 print(a + b) In this example, the variables a and b are added and the result is returned as a float value. 1.5 + 1.5 = 3.0 3.0

add complex numbers

If complex numbers are added in Python, the result is returned as a complex number. # add complex number a, b = complex(2, 3), complex(4, 5) print(a + b) In this example, the complex numbers a and b are added and the result is returned as a complex number. (6+8j)

add strings

If we use the + operator on strings, the strings are concatenated. # concatenate strings using the + operator a, b = 'hello', 'world' print(a + b) In this example strings, a and b are concatenated and the result is printed. helloworld Only strings and strings can be concatenated. Convert other types to strings first before concatenating them. If a string is concatenated with another type for example an integer, a TypeError exception is raised. TypeError: can only concatenate str (not "int") to str To prevent this exception, convert all elements to string type first. # convert to string and concatenate a, b = 'High', 5 print(a + str(b)) In this example, the integer 5 is stored as variable b. Before it can be concatenated with variable a, it is necessary to convert it to a string. To convert it to a string the str() function is used. Finally, the result is printed. High5

add lists

If the + operator is used on lists all elements of the lists are combined into one list. # add lists list1 = [1, 2, 3] list2 = [4, 5, 6] print(list1 + list2) In this example, all elements of both lists are combined into one list. The result is returned as a list containing all elements. [1, 2, 3, 4, 5, 6] To add the elements of lists instead, use the zip() function as shown below. # add element of lists list1 = [1, 2, 3] list2 = [4, 5, 6] list3 = [] for n1, n2 in zip(list1, list2): list3.append(n1 + n2) print(list3) In this example, three lists are created. Two lists containing the original numbers and one list for the results. The zip() function is used to add the element. The list.append() method is used to append the results to list. Finally, the list3 containing the results is printed. [5, 7, 9]

                
        

Summary


Click to jump to section