PyLearn / Add and Subtract



Welcome to PyLearn once again! In this tutorial I will teach you how to perform addition and subtraction on two or more numbers in Python.


It is very important to add and subtract to numbers in a computer program. Suppose you are a scientist or mathematician and have to add a huge number of very large numbers with utmost accuracy. What will you do in such a situation? Simply taking out your notebook and summing will be a very tedious job. What will be the easiest in such a situation is to just create a simple computer program in Python. This is explained below:


print (2 + 2)


In the program given above, we have just added two simple numbers, i.e. 2 and 2 and the preceding program will print the following:


Output: 4


In this program we have typed in the print statement and inside the parentheses we have typed in the numbers to add separated by the “addition” operator. Similarly you can also subtract one number from the other by just replacing the addition operator (+) by the subtraction operator (-). It is very important to note that we must omit the quotation marks or you will get the output as 2 + 2. Similarly you can also add strings in a program. This is called “Concatenation”. An example is given below:


print (“Good ” + “morning”)


Output: Good morning


The program just adds the two strings one after the other. You might also have observed that I have given space between the word Good and the closing quotation mark. This is because if there was no space then it would print “Goodmorning” on the screen. I could have also given the space before the word morning wherever you give the space you will not run into an error I this way you can also concatenate numbers in the form of strings. For example, if you take the first program and put the each number within the quotation marks, then output will not be 4 but 22. It is however not possible to subtract one string from the other.


In the next lesson I will explain multiplication and division in Python. Thanks!!


Next Lesson:



Previous Lesson: