10: Operations – I (Arithmetic)
Operations – I (Arithmetic)
Operation is another vital part of an algorithm. In fact, we can say that every algorithm is performing operations on data. Data is stored in variables so we perform operations on these variables. There are many types of operations in Python but for the extent of this course we will study three fundamental operations. Arithmetic is the first and most widely used.
- Every operation has two components.
- Operand(s)
- Operator(s)
- Operands are variables or just values which are required to be operated.
- Operators are symbols that show an operation.
- After an operation, we have the result and we can use this result for further operation or display.
- Every language has its own set of operators. Many operators are similar but some may be different in different languages.
Assignment Operator
- Assignment operator = is the fundamental operator of any programming language.
- This operator has at least two operands.
- The left-hand-side of the assignment operator must be variable.
- The right-hand-side is called an expression. It may be a simple value, variable or even more than one variable and value.
- The operator evaluates the expression on the right-hand-side and saves it to the variable on the left-hand-side.
val1 = 10val2 = val1
Code 2: Assigning Value and Value of a Variable to Other Variable
- On line 1 we create a variable val1 and store 10 in it.
- We have = symbol between val1 and 10.
- val1 (on left-hand-side) is the variable.
- 10 (on the right-hand-side) is an expression.
- Both val1 and 10 are operands and = is operator
- When this line is executed, the computer (CPU) will evaluate the expression in the right-hand-side.
- After evaluation it find 10 so this number will be store into val1
- The expression on the right-hand-side is very simple and not required to calculate but we will study complex examples later in this lecture.
- On line 2; we can find that both operands are variables.
- The CPU performs a similar operation; first it evaluates the right-hand-size expression which is a variable val1 and it contains value 10 (from line 1).
- The value of val1 will be assigned to val2.
- Finally, val2 also has 10.
- The assignment operator works with all kinds of data.
Arithmetic Operations
- Arithmetic operations are only for numeric data types (integer and float). These operators cannot be used for string or bool.
- Only + can be used for strings.
- There are a total of 7 arithmetic operators in Python. These are also called algebraic operations.
- + (Addition)
- – (Subtraction)
- * (Multiplication)
- / (Division)
- // (Floor Division)
- % (Modulus or Remainder)
- ** (Power or Exponent)
- Addition operator (+) performs simple sum two variables or values or both.
val1 = 10val2 = 20result = val1 + val2print (f"The sum of {val1} and {val2} is {result}.")result = val1 + 2print (f"The sum of {val1} and 2 is {result}.")result = 2 - 5print (f"The result of 2 minus 5 is {result}.")
Code 2: The Addition (+) Operation
- We have created two variables and assigned them two different values.
- On line 3 we use + operator to sum these values and on the same line we use assignment operator.
- On the left-hand-side the variable result is here.
- On the right-hand-side we have an expression val1 + val2.
- CPU will evaluate the expression on right-hand-size and find that the sum of both numbers is 30. The answer will be stored in the variable result.
- On the next line we will print.
- On line 6; we are calculating the sum of variable and a value 2 and again storing it into the result variable and then printing on the next line.
- Similarly, on line 7 we are using both values (no variable this time) and store their answer into the result variable in a similar way and print the output.
Figure 1: Output of Code 1
- Commutative law also prevails here for addition as it prevails for normal arithmetic.
- Subtraction (-), multiplication (*) and the rest of the operations work similarly.
- If any of the numbers is float in the expression then the result will also be float.
val1 = 10.2val2 = 3result = val1 + val2
Code 3: Operation Between Integer and Float
- The answer will be 13.2 which is float number
- Handle the division operator (/) with some care.
- If the fraction produced between two values is unlimited then it will print up to 16 digits.
val1 = 10val2 = 3result = val1 / val2print (f"The result of dividing {val1} by {val2} is {result}.")
Code 4: Division produce unlimited fraction
Figure 2: Output of Code 4
- Zero denominator will cause error in division process.
- We can use formatting of float values in string interpolation.
val1 = 20val2 = 3result = val1 / val2print (f"The result of dividing {val1} by {val2} is {result:.4f}.")
Code 5: Using String Interpolation with Float Values
- The result will be an unlimited fraction which shows 16 digits after the decimal point but we want to restrict it to only 4 digits.
- We use {result:.4f}. Here the .4f means to show 4 digits after decimal point. You can change this number according to your requirements.
- Floor division (//) will automatically round down.
val1 = 20val2 = 3result = val1 // val2print (f"The result of dividing {val1} by {val2} is {result}.")
Code 6: Only Integer Answer After Division
- The value of the result will be displayed 6 because the actual result is 6.666… and this will round floor to 6.
- The Modulus Operator (%) provides a remainder instead of quotient.
val1 = 20val2 = 3result = val1 % val2print (f"The result is {result}.")
Code 7: Using Modulus Operator
- The result will be 2 because the operator will divide the 20 by 3. As 3 x 6 is 18 which is the nearest multiple of 3 to 20 and the difference between 20 and 18 is 2 so the answer will be 2.
- Modulus Operators also work with float values.
- Python have (**) operator that calculates the exponent of power like 2^3 = 8.
val1 = 2val2 = 3result = val1 ** val2print (f"The result is {result}.")
Code 8: Using Power Operator
- This operator is very useful in scientific calculations.
- Multiple arithmetic operations can be performed in a single line like algebraic expression.
val1 = 2val2 = 3val3 = 4result = val1 + val2 – val3print (f"The result is {result}.")
Code 9: Implementing Expression in Python
- The answer will be 1 because first 2 and 3 will be added and then 4 will be subtracted.
Operator Order
- As mentioned, multiple operations can be performed on a single line so operation order is defined.
- According to rules of arithmetic, the top order is multiplication-based operations like multiplication, division, floor division, modulus and power while addition-based operation have lower order.
- For example, the following will produce 10. Because first, 3 will be multiply to 2 and then add 4
ans = 4 + 3 * 2print (f"The answer is {ans}.")
Code 10: Multiplication has Higher Preference than Addition.
- We can also change the precedence by using parenthesis ().
- The following expression will produce 14 because the addition process between 4 and 3 will be performed first as it is enclosed in parenthesis.
ans = (4 + 3) * 2print (f"The answer is {ans}.")
Code 11: Parenthesis will the Operation Order
After completing the concepts of variables, data types and arithmetic operators, we are able to solve some real-world problems. Now we can build a minimalistic algorithm. Let’s see some examples
Real World Examples
Example 1: Write a program that calculates the area of a square. The formula for area is area = height . width
Values of height and width will be enter by user
Solution:
- For solving this problem, we have to perform following steps
- According to requirements we must have two variables, h and w
- We have to enter the value into these variables
- Multiply these variables and result should store in variable a
- Display the result
- The above four steps are pseudocode of the desired algorithm.
- Now open VS Code, create a new file “area_calc.py” and write the following code in it.
h = int (input ("Enter the height: "))w = int (input ("Enter the width: "))a = h * wprint ("The area is: ", a)
Code 12: Area Calculation
Figure 3: Output of Area Program
Example 2: Calculate the net price of an item. The sales tax will apply on 10% of actual price, VAT (Value Added Tax will be 2%. VAT will apply on item price after sales tax. 5% discount from manufacturer on actual price. The price of the item will be entered by the user.
Solution:
- This is a little bit of a complex scenario because it has more than one step.
- Taxes will be added (sales tax and vat) in the price and discount will be subtracted.
- We have to calculate the amount of taxes and discount before addition and subtraction because a percentage is given.
- This would be the pseudocode of the above problem.
- Input the item price from the user.
- Calculate 10% sales tax on item price.
- Add this sales tax value to item price (item price + sales tax).
- Calculate 2% VAT on the sum of price and sales tax.
- Calculate 5% discount of actual item price.
- Net price = item price + sales tax + vat – discount
- Print the item net price
- This code reflects your pseudocode.
item_price = int (input ("Enter the price of the item: "))sales_tax_percent = 0.1sales_tax_amount = sales_tax_percent * item_pricegross_price = item_price + sales_tax_amountvat_percent = 0.02vat_amount = vat_percent * gross_pricediscout_percent = 0.05discount_amount = discout_percent * item_pricefinal_price = gross_price + vat_amount - discount_amountprint ("The final price of the item is:", final_price)
Code 13: Calculating Net Price of a Product
- On line 1 we input the item price.
- First, we calculate the sales tax according to 10% of item price. We set 10% in line 2 and then multiply this value with item price to find the sales tax amount.
- We need to sum the item price and sales tax to find VAT. We add these values and save the answer in gross_price.
- As VAT is 2% of gross price, we set the vat to 0.02 and then multiply it with gross_price to find the amount of VAT.
- Discount is 5% which is on actual item price so, we calculate it by multiplying the actual price with discount_percent.
- For final_price we sum the gross price (actual price with sales tax) with VAT amount and subtract the discount.
- Print the final price.
Example 3: Write a program that finds the sum of digits of a three-digit number. The number will be entered by the user. For example, if a user enters 729 then the answer will be 18 because 7 + 2 + 9 = 18.
Solution:
- This is a simple but tricky question that belongs to arithmetic games.
- To solve this kind of problem, we should understand the working of arithmetic operators.
- Regularly solving these kinds of problems makes you a better and crafty software engineer.
- Following is the pseudocode
- Input an integer from the user. Also display that the user must enter only a 3-digit number.
- As this is a 3-digit number we have to perform an arithmetic operation three times that strips the number into three parts.
- Modulus and division operators will help us
- If we divide the number (such as 729) by 100 then we will get 7.29. if we convert this number into integer then we will get 7 only that is the first digit. We can save this digit into some variable.
- If we take the remainder of 729 with 100 then we will get 29 as remainer. We should store this number to get 2 for next.
- Now take divide 29 (the number we get from step e) then 2.9 will get and convert it into integer so get 2. Save it as a second digit.
- Again, take the remainder of 29 with 10 and get 9.
- Save the number 9 in variable.
- Sum all the digits and save the result in variable and print as the last step.
number = int (input ("Enter a 3-digit number: "))digit1 = int (number / 100)number = number % 100digit2 = int (number / 10)digit3 = number % 10digit_sum = digit1 + digit2 + digit3print ("The sum of the digits is:", digit_sum)
Code 14: Calculating Sum of Digits of a Number
- First, we enter an integer number, for example 729
- On line 2, we find the quotient of this number by 100 and also convert it to integer. This process will provide us 7 and store it in the digit1 variable.
- In the next line we again use the number variable to store the remainder of 729 with 100 which is 29. We can use some different variables but for the efficiency of the program, we reuse the variable.
- We again divide this number 29 by 10 and get 2 by converting the answer into integer and saving it into digit2.
- Then we take modulus 29 with 10 to get 9 into digit3.
- Now we have all three digits 7, 2 and 9 into different variables and we can sum this number and store the result in digit_sum.
- Print the result.








