Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Numbers and Variables: Python Does the Math 35

Floating-point, or decimal, numbers are great when we want
fractions, like 3.5 miles, 1.25 pizzas, or $25.97. Of course, in
Python, we don’t include the units (miles, pizzas, dollars), just the
number with the decimal. So if we want to store a variable with
the cost of our pizza (cost_of_pizza), we might assign it as follows:
cost_of_pizza = 25.97. We’ll just have to remember that the units
we’re using there are dollars, euros, or some other currency.


Python Operators


The math symbols like + (plus) and - (minus) are called operators
because they operate, or perform calculations, on the numbers in
our equation. When we say “4 + 2” aloud or enter it on our calcu-
lator, we want to perform addition on the numbers 4 and 2 to get
their sum, 6.
Python uses most of the same operators that you would use
in a math class, including +, -, and parentheses, (), as shown in
Table 3-1. However, some operators are different from what you
may have used in school, like the multiplication operator (the
asterisk, *, instead of ×) and the division operator (the forward
slash, /, instead of ÷). We’ll get to know these operators better in
this section.


Table 3-1: Basic Math Operators in Python


Math
symbol

Python
operator

Operation Example Result

+ + Addition 4 + 2 6




    • Subtraction 4 - 2 2
      × Multiplication 4 2 8
      ÷ / Division 4 / 2 2.0
      42 Exponent or power 4 2 16
      ( ) () Parentheses
      (grouping)




(4 + 2) * 3 18
Free download pdf