/* jquery */ /* jquery accordion style*/ /* jquery init */

26 March 2013

Learn Python - Assigning Variables

In math equations we can assign values to symbols. We can do the same in Python using something called variables. Let's consider a simple math problem.

We've seen a mobile phone contract that offers a free phone plus plenty of free texts and call minutes. However, we are undecided whether to go for a 18 or 24 month deal. We know the price of a phone is normally £160, so let's store this value in a suitably named variable:

>>> phone = 160

We can check the value of 'phone' by using a simple print statement, like this:

>>> print phone

Having confirmed the 'phone' value is 160, we can calculate the 24 month deal, which costs £12 a month, and deduct the phone cost. We'll store the result of this calculation in a new variable called 'months24':

>>> months24 = (24 * 12) - phone

Next we'll do a similar calculation for the 18 month deal, which costs £15 a month, and again deduct the phone cost. The result is stored in another variable called 'months18':

>>> months18 = (18 * 15) - phone

Let's print out each of these deals:

>>> months24
>>> months18

The output shows how much we are really paying for those 'free' minutes and texts, after discounting the phone cost. Now let's compare the difference between these deals:

>>> months24 - months18

Now we can see the 24 month deal is only £18 more for an extra 6 months of calls and texts - a pretty good deal.

A post from my Learn Python on the Raspberry Pi tutorial.

No comments: