Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 2: Arithmetic Operators

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

Video Tutorial

Python 3 Changes

print(x,y) instead of print x, y

In Python 3, "/" uniformly works as a float division operator. So, it always returns the float type:
  • 10/3 returns 3.333333 instead of 3,
  • 6/3 returns 2.0 instead of 2.
No more confusion!

Video Summary

  • 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. This changed in Python 3. See the note above.

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)
    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)
      >>> print(3 - 4)
      >>> print(5 * 6)
      >>> print(7 / 8)