Python #5 Mathematical Operators

This is just a quick post about maths in Python. Computer languages use slightly different symbols for mathematical operations. Here’s a few examples from Python 3.

The easiest way to see this working is to use the interpreter (the first window that opens up when you start Python – the one with >>>).

Adding and taking away are the same:Β  just type: Β “1+1” and : “1-1” and you’ll see.

Multiplcation is done by the * symbol. Division by /. Try a few out!

There are some other nice division operators that might be new to you. // gives the integer division. So if you type 7//2 you should get the answer “3”. The other one is called “modulus”. This gives the remainder after division has happened, so 7%2 will return “1”.

There are also some shortcuts you can do. If you want to add a number to a variable and then put the answer back in the variable you can do it this way. Let’s say you have put the value 1 into a variable i (type in “i=1” and hit enter). Now type “i+=5” and press enter. If you now tell the interpreter to “print(i)”, it will give you the answer “6”. You can do this with the other operators I’ve mentioned also. Have a play! You might even want to write a simple program that does something like asking for some numbers, doing some sums with them, and then printing the results.

antiloquax

Advertisements

Tags: , ,

5 Responses to “Python #5 Mathematical Operators”

  1. foobie Says:

    s/valuable/variable/ πŸ™‚

    or more pythonny:
    import re
    txt = re.sub( “valuable”, “variable”, txt )

  2. antiloquax Says:

    Thanks for your comment, foobie. I don’t understand it though!

  3. foobie Says:

    Sorry – was just pointing out a typo (“If you want to add a number to a valuable”) πŸ™‚

    new_string = re.sub( ‘search’, ‘replace’, original_string )

    ‘traditional’ regex syntax is s/search/replace/

    HTH πŸ™‚

  4. antiloquax Says:

    Hi foobie – thanks, I’ll correct the typo!

  5. Programming Lesson « 100mudcats Says:

    […] you are feeling confident, you might like to look at some other tutorial posts over on Team Python. This one has some more information about mathematical […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: