Python Tutorial-Operators

An operator simply stated setting something equal to a value. Think of it like you were in grade school. If you were given a math question like 3 + 2 = ? and asked what the answer was you would respond 5 (I hope). That is what’s known as a math operation.

All programming languages use operators. Python is no different in that sense. Python uses 5 different areas of operators, vaguely described as: arithmetic, assignment, increment/decrement, comparison and logical. Let’s jump into it.

In my example of a math operator above I used 3 + 2. Typing the code above into IDLE and pressing enter will return 5.

This example will return 6.

This will return 3.

This will return 1. Wait, what did you just say? I don’t get it. Alright, let me explain. The % is the modulus operator. This is the equivalent of a remainder when you learned division in grade school. When you figured out what 9/4 was you would get 2 with a remainder of 1.

Now let’s put it to a little use.

What did you get? Did you get an error? If you did then you copied and pasted this into IDLE. Remember IDLE can only read one statement at a time so you have to type out each line and press enter to get your answer. If you want to enter them all together you have to use the Python Shell as reviewed in the comments tutorial. You should have had the following answers:


Now try this.

You should return 9

Finally, one last exercise for operators (for now).

Notice how I combined the last tutorial and this one? The first print statement should return 7.3. Because we made one of the numbers a float value Python automatically sets the answer to a float value. By adding the int in front of the print statement casts the result as an integer. Your result should be 7.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.