Sign InCoursewareNuggetsTutorials CoursesCodePad

Python Can Do Math!

Tali is hungry. She sees a vending machine and wants to buy a bag of chips that costs $1.25 and a bottle of water that costs $1.00. Andrew gives her four $1 bills and asks her to buy a bag of chips for him as well. How much is the change? Tali calculates it like this:

total cost:  1.25 x 2 + 1.00 = 3.50  
total money: 1.00 x 4 = 4.00
change: 4.00 - 3.50 = 0.50

This is easy enough to do by hand. Tali uses two types of numbers here: integers (like 4) and decimals (like 1.25).

We can also use computer programs to calculate this kind of math problem. With a computer's power, we can do more complicated math very fast. Python uses the number type integer or int to represent integer values and the number type floating-point or float to represent decimal values. The math operations (addition, subtraction, multiplication, and division) are performed by operators using symbols (+, -, *, /). In Python, the multiplication symbol is an asterisk (*) and the division symbol is a forward slash (/). Lastly, the modulus operator (%) gives the remainder of the division. For example, 3 % 7 = 3, because 3 divided by 7 is 0 with remainder 3, and 9 % 7 = 2, because 9 divided by 7 is 1 with remainder 2. Now Let's write a Python program to print out total cost, total money, and change.

print(1.25 * 2 + 1.00) print(1.00 * 4) print(1.00 * 4 - (1.25 * 2 + 1.00))

The above program is not very efficiently written. Total money and total cost are calculated twice. Can we avoid doing that? Yes - that's why we use variables!

total_cost = 1.25 * 2 + 1.00 total_money = 1.00 * 4 change = total_money - total_cost print(total_cost, total_money, change)

Operators and Operands
TipOperators are special symbols that represent computations like addition, subtraction, multiplication and division. The values the operator works on are called operands.
© CS Wonders·About·Gallery·Fun Facts·Cheatsheet