Using Variables in Python
In this example, we demonstrate the use of variables in Python computations. We wish to find the area of a triangle with side lengths 100, 150, and 200cm. Rather than repeatedly using these numbers, define a, b, and c respectively as 100, 150, and 200 by simply typing a=100, b=150, and c=200. We can use these variables to define other variables such as the semiperimeter, s, which is a + b + c all divided by 2. Finally, we find the area of the triangle using the formula Area=ss−as−bs−c. Refer to Python’s help on Basic Functions to discover that sqrt returns the square root of the expression following in parentheses. Also notice that a variable name can consist of more than one letter, such as Area. Notice that no output is displayed when we press SHIFT/ENTER. To see the answer, use the print command. You can also include explanatory text in either single quotes or double quotes so readers can understand the meaning of your output, and remember to use .evalf() after the variable name if you want a decimal approximation. Note that Python is case sensitive, meaning that uppercase letters are different variables from lowercase. So, for instance, if we assign a value of 6 to area (with a lowercase ‘a’), our value of Area (with an uppercase ‘A’) remains unchanged. Using variables to define expressions in Python will be very helpful as you write more complicated programs.