Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#3: Arithmetic Operators

                          << Previous Tutorial           Next Tutorial >>
On this page: print, arithmetic operators (+, -, %, *, /, **). Script vs. shell environment.

Get Started

Video Summary

  • Script found here. Shell output from the script, followed by an interactive shell session.
  • In a script environment, the "print" command must be explicitly given in order for the result to be printed out.
  • Basic operations: "+" is used for addition, "-" for subtraction, "*" for multiplication, "/" for division, "%" for remainder.
  • "^" is NOT used for exponents, it is a bitwise operator (NOTE: you don't need to know this). For exponents, use "**".
  • The division operator "/" works as integer division if both inputs are integers. Therefore, 5/3 returns 1. You must supply a floating point number ('float') with decimal points if an answer other than a whole number is desired: 5.0/3 returns 1.666666.

Learn More

  • You can turn an integer into a floating number using the float() function. For example, float(5) returns 5.0.
  • As you have seen, there are two major types of Python programming environment: (1) script, and (2) shell. It might be confusing now, but it is important to keep them separate.
    1. A Python script is a stand-alone file, typically with a .py extension (ex. ep_04.py) that you save on your local machine. You will execute the file to produce the output. Because it is saved as a file, you can re-run it to produce the same results. Throughout this tutorial, a script file will be shown like this, with the file name shown at the bottom right:
      print 1 + 2
      print 3 - 4
      print 5 * 6
      print 7 / 8
      foo.py
      
    2. An interactive shell is a Python programming environment where you interact directly with the Python interpreter. Here, each command you enter gets parsed by the Python interpreter which displays the result right away. A shell session will be shown like this (note the command prompt >>>):
       
      >>> print 1 + 3
      4
      >>> print 3 - 4
      -1
      >>> print 5 * 6
      30
      >>> print 7 / 8
      0
      

Explore