Getting Started with Python

Jump To

Starting IDLE, the Python IDE

Most implementations of modern programming languages come with an Integrated Development Environment (IDE). An IDE provides the programmer with various tools — such as a text editor, a compiler or interpreter, or a debugger — to write and test programs. Python’s IDE is called IDLE (see here for an explanation).

When you first start IDLE, you will probably see a screen similar to the following.

Python 3.1.2 (release31-maint, Sep 17 2010, 20:27:33)
[GCC 4.4.5] on linux2
Type "copyright", "credits" or "license()" for more information.
==== No Subprocess ====
>>>

Don’t worry if the numbers aren’t the same. They tell you information about the version of Python being used (3.1.2 in this case), the date it was released (September 2010) and the system (linux) being used. For now, the three “greater than” symbols (>>>) tell you that Python is waiting for you to do something. These symbols are called the prompt.

Well, OK then. Let’s do something!

Python and Simple Mathematics

Let’s try entering a number to see what happens. For example, I might choose 42.

>>> 42
42

Well, that wasn’t very helpful. Python repeated (or echoed) the number, but that’s all. What if you enter a letter instead?

>>> A
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in 
    A
NameError: name 'A' is not defined

Yikes! This is an example of an error message. Whenever Python encounters a serious problem, it stops what it is doing and displays a message similar to the one above. Sometimes these messages can be tricky to decipher, but in this case it is not too hard. The error occurs on line 1 (because our “programs” are only one line long at this point), and occurs because the letter A is not “defined”. So, Python has no knowledge of what the letter A is. We’ll talk more about the different types of errors later, but for now, know that you will be seeing these fairly often as you learn how to program. With practice, you should be able to reduce the frequency of these messages.

OK, so letters are off-limits for now. Let’s go back to numbers, and try to add two of them together.

>>> 3+5
8

Good. At least Python can perform simple mathematics. Of course, this isn’t a huge surprise because computers are very good at performing mathematical calculations. It’s what they were originally designed to do, long before video games and streaming video had been developed. Let’s try some more calculations.

>>> 6-9
-3
>>> 2*4
8
>>> 7/2
3.5

Everything looks as it should. Notice that Python is aware of negative values (-3), and can handle decimal numbers when dividing. In earlier versions of Python, 7/2 would have returned 3, since 2 goes into 7 three full times (with a remainder of 1). You can achieve the same thing in Python 3.x by using two slashes instead of one.

>>> 7//2
3

What about the remainder? Python uses the % symbol, called the modulus operator, to calculate the remainder when one integer is divided by another.

>>> 7%2
1

While you may not have had much experience with this type of division in high school, it is surprisingly useful in computer science. We will talk about some applications of using the modulus operator later.

OK, how about exponents? Let’s try squaring a number using two different methods. On some scientific calculators, the caret (^) indicates an exponent.

>>> 5*5
25
>>> 5^2
7

Hmmm, that’s not good. Surely Python can handle a simple exponent! It can, but it uses a slightly different notation. Python uses two asterisks (**) to indicate exponentiation. This kind of makes sense, since exponentiation is really just multiplication anyway, so think of ** as a kind of “super-multiplication” in a sense.

>>> 5**2
25

Ahhh, much better. This is a good example of how a language’s syntax — its notation and structure — may be different than another’s.

Just like in mathematics, Python abides by the order of operations (BEDMAS or PEMDAS). This makes it possible to chain multiple operations together.

>>> 6+8/2
10.0

Note that division was performed before addition. To change the order, use brackets (parentheses) as necessary.

>>> (6+8)/2
7.0
>>> 6+(8/2)
10.0

In both examples above, Python expresses the answer as a decimal, even though the result is an integer value. We will talk about the different data types later.

The mathematical operators we’ve looked at so far are summarized in the table below.

Operator Description Example Result
+ addition 2+5 7
- subtraction 9-1 8
* multiplication 3*9 27
/ division 9/4 2.25
// integer division 14//3 4
% modulus (remainder) 14%3 2
** exponentiation 2**3 8

Since many programs incorporate mathematics into their designs, it is important to be familiar with the syntax for these basic operations.

Exercises

  1. Use IDLE to calculate each expression, where possible.
  2. Determine the quotient and remainder for each of the following.

More Math Using the math Module

Let’s say we want to calculate the square root of 42. We know that the answer is somewhere between 6 and 7, but we would like to know the answer to a few decimal places. You might try typing something like the following.

>>> sqrt(42)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in 
    sqrt(42)
NameError: name 'sqrt' is not defined

Hmmm. The error message claims that there is no function called sqrt; however, it does exist. The problem is that sqrt is not a built-in function. Python only loads a small number of functions on start-up, in order to save memory. All other functions are stored in modules, which are just Python files, and must be imported first.

To import the math module, use the import command.

>>> import math

Now, it might seem like nothing has happened; however, Python has loaded all of the functions contained in the math module behind-the-scenes. If there was an error — say, from trying to load a module that does not exist — you would see an error as follows.

>>> import ThisModuleDoesNotExist
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in 
    import ThisModuleDoesNotExist
ImportError: No module named ThisModuleDoesNotExist

OK, now we can calculate the square root of 42.

>>> sqrt(42)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in 
    sqrt(9)
NameError: name 'sqrt' is not defined

Ack! Why can’t Python find the function we just imported?

To reference a function that has been imported, we must prefix (attach to the front) the function with the name of the module in which it is stored. This points Python toward the correct file.

>>> math.sqrt(42)
6.48074069840786

There we go! Let’s try another.

>>> math.sqrt(9)
3.0

Note that the square root function always returns a decimal answer, even if the result is an integer. We will talk more about data types, and how to convert from one type to another, shortly.

The math module contains various mathematical functions. It also contains two important constants: pi and e. Most people are familiar with pi. e often arises in financial scientific applications.

>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045

Both constants are irrational numbers, so their values are only approximations.

Functions for trigonometry are also included in the math module. For example, we know that the sine of 30 degrees is 0.5.

>>> math.sin(30)
-0.9880316240928618

Hmmm, that’s not right. Except that it is. It’s just not what was expected. By default, trigonometric functions in the math module work in radians. Radians are simply another unit of measurement for angles. If you’ve never worked with radians before, you can get a quick overview here. To convert an angle from degrees to radians, use the radians function.

>>> math.radians(30)
0.5235987755982988
>>> math.sin(0.5235987755982988)
0.49999999999999994

Note that the value is not 0.5 as we expected it to be. This is because of the way in which computers store decimal values. They are not always precise, and are often subject to rounding errors. More on this later. Rather than typing in the radians manually, we could also have achieved the same result using a single line.

>>> math.sin(math.radians(30))
0.49999999999999994

This is an example of nesting functions — placing one function inside of another. This will prove useful later on.

To calculate the inverse trigonometric functions, often denoted as sin-1 on calculators, use the older terminology arcsine, abbreviated asin.

>>> math.degrees(math.asin(0.5))
30.000000000000004

Logarithmic and exponential calculations can also be made using the functions in the math module. For logarithms with a base of 10, use log10. For a specified base, use log. ex can be computed using exp.

>>> math.log10(100)
2.0
>>> math.log(8,2)
3.0
>>> math.exp(1)
2.718281828459045

Some other useful functions, dealing with integers, are the floor and ceiling functions, which round down and up respectively. These are typically denoted and . Another useful function is for factorials, where n factorial is defined as .

>>> math.floor(4.9)
4
>>> math.ceil(3.1)
4
>>> math.factorial(4)
24
>>> 4*3*2*1
24

Some of the mathematical functions in the math module are summarized below.

0.0

Function Description Example Result
sqrt square root of x math.sqrt(16) 4.0
sin sine of x, in radians math.sin(0) 0.0
cos cosine of x, in radians math.cos(0) 1.0
tan tangent of x, in radians math.tan(1) 1.5574077246549023
asin arcsine (inverse of sine) math.asin(0.5) 0.5235987755982989
acos arccosine (inverse of cosine) math.acos(1)(
atan arctangent (inverse of tangent) math.atan(100) 1.5607966601082315
radians convert degrees to radians math.radians(180) 3.141592653589793
degrees convert radians to degrees math.degrees(math.pi) 180.0
log10 calculate log, base 10 math.log10(1000) 3.0
log calculate log, base specified math.log(32,2) 5.0
exp calculate ex math.exp(2) 7.38905609893065
floor round down to nearest integer math.floor(6.5) 6
ceil round up to nearest integer math.ceil(6.5) 7
factorial calculate x! math.factorial(5) 120

You can learn about all of the other mathematical functions available in the math library here.

Exercises

  1. Use IDLE to calculate each expression, where possible.
  2. Perform each conversion as indicated.
    1. to radians
    2. to radians
    3. to radians
    4. radians to degrees
    5. radians to degrees
    6. radians to degrees
  3. Convert each measure from degrees to radians, then calculate each ratio.
  4. Calculate each angle, given the indicated ratio, then convert your answers to degrees.

Variables and Data Types

A variable is a name given to a particular value. This value may or may not change during program execution.

To create (or declare) a variable, assign it a value.

>>> number = 42

The equals sign, =, is called the assignment operator, since it is used to assign a value to a variable. This reserves space in main memory, which stores the actual value of the variable.

We can now refer to the variable by its name, anytime we want. For example, to check its current value, type the variable’s name.

>>> number
42

We can perform mathematical operations using the variable’s value.

>>> number - 10
32
>>> number
42

Notice that the variable retained its value, even after the subtraction. A variable will not change its value unless it is reassigned a new value by a subsequent command.

>>> number = 15
>>> number
15
>>> number = number + 5
>>> number
20

In mathematics, variables often have short one or two letter names; however, in most programs, variables have longer, more descriptive names that describe what they represent. The following are all good variable names.

>>> age = 16
>>> price = 3.50
>>> taxRate = 0.13

The last example is a good example of how multiple words can be strung together in a readable manner. Another alternative is to use underscores between the words.

>>> number_of_players = 4

Variable names may consist of letters, numbers and underscores. They cannot begin with a number, nor can they contain spaces. Also, they cannot be any of the following Python keywords, since they are integral to the interpreter’s operation.

True      False   None   and    as      assert  break    class
continue  def     del   elif    else    except  finally  for
from      global  if    import  in      is      lambda   nonlocal
not       or      pass  raise   return  try     while    with
yield

Here are some examples of inappropriate variable names.

>>> 2nd_place=2
SyntaxError: invalid syntax
>>> number of people = 10
SyntaxError: invalid syntax
>>> class = 7
SyntaxError: invalid syntax

Each variable holds a value (or values) of a certain type. To check a variable’s type, use the type function.

>>> type(number)
<class 'int'>

The variable number is an integer, one of three numeric types in Python. The other two numeric types are floating point numbers (aka decimals) and complex numbers.

>>> Pi = 3.14159
>>> type(Pi)
<class 'float'>

Python also has sequence types. The most common of these are strings, which are sequences of characters. Strings are always indicated by single or double quotes. Other sequences, including tuples and lists, will be covered later.

>>> name = "Jon"
>>> type(name)
<class 'str'>

Some operations only make sense using certain data types. For example, it is possible to add two integers, or two floats, or even an integer and a float.

>>> A = 3
>>> B = 6
>>> C = 5.5
>>> type(A)
<class 'int'>
>>> type(B)
<class 'int'>
>>> type(C)
<class 'float'>
>>> A+B
9
>>> A+C
8.5

It does not make sense, however, to add an integer and a string.

>>> D = "hello"
>>> A+D
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    A+D
TypeError: unsupported operand type(s) for +: 'int' and 'str'

You may have noticed earlier that division, /, always returns a float, even when the result is an integral value. To obtain an integer result, use // for integer division.

>>> B/A
2.0
>>> B//A
2

This may seem trivial, from a mathematical perspective, but in Python it is not. Certain functions only operate with particular data types. In this case, it might be necessary to convert one data type to another. This is known as typecasting. For example, to convert to an integer, use the int function.

>>> X = 4.0
>>> type(X)
<class 'float'>
>>> X = int(X)
>>> X
4
>>> type(X)
<class 'int'>

Let’s try some more.

>>> Y = 3.5
>>> type(Y)
<class 'float'>
>>> Y = int(Y)
>>> Y
3
>>> type(Y)
<class 'int'>
>>> Z = "12 o'clock"
>>> type(Z)
<class 'str'>
>>> Z = int(Z)
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    Z = int(Z)
ValueError: invalid literal for int() with base 10: "12 o'clock"

Floating point values are converted into integers by truncating everything after the decimal point, while strings cannot be converted to integers unless they are composed solely of integers.

Exercises

  1. Which of the following are acceptable variable names in Python? If a name is not acceptable, explain why.
    1. P
    2. bestFriend
    3. 12jurors
    4. Bx3R28
    5. True
    6. true
    7. test score
    8. soup_of_the_day
    9. #ofPlayers
  2. State the final value of A after the sequence of commands.
    1. >>> A = 25
      >>> B = 12
      >>> A - B
      13
      
    2. >>> A = 25
      >>> B = 20
      >>> A = B
      
    3. >>> A = 25
      >>> B = 12
      >>> A = A + B
      
  3. State each variable’s data type.
    1. U = "Python"
    2. W = 1.625
    3. X = 3/2
    4. Y = 5**2
    5. Z = "285"
  4. Determine the resulting type and value of each command.
    1. favouriteNumber = float(2.71)
    2. tastyPi = int(3.14159)
    3. firstFiveDigits = str(12345)
    4. lastName = int("Garvin")
    5. solution = int(12/4)
    6. answer = float(7//2)

More Work With Variables

As programs get more complex, the number of variables generally increases. Let’s assume that a program declares three variables, assigning them all an initial value of 7. The following code will do this.

>>> A = 7
>>> B = 7
>>> C = 7
>>> A
7
>>> B
7
>>> C
7

Instead of typing the same command three times, it’s possible to assign the same value to multiple variables at the same time.

>>> A = B = C = 7
>>> A
7
>>> B
7
>>> C
7

This works well for a small number of variables, but for greater quantities it is pretty inefficient. Different values can be assigned to multiple variables as well, using commas to separate each variable or value.

>>> C, D = 2, 5
>>> C
2
>>> D
5

When assigning multiple values, make sure you have one value for each variable. Also, it is not possible to assign two or more variables the same value unless it is included once per variable.

>>> E, F = 1, 2, 3
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    E, F = 1, 2, 3
ValueError: too many values to unpack
>>> G, H = 3
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    G, H = 3
TypeError: 'int' object is not iterable

Recall from earlier that, unlike in mathematics, a variable may change its value during program execution. This is handy when we do not want to create multiple variables to represent the same thing. For example, a variable might be used as a counter from 1 to 10 — it would be silly to use ten variables!

Let’s say we wanted to start the counter at 1, and increment it by one number at a time. Our code might begin something like this:

>>> counter = 1
>>> counter = counter + 1

This would update the value of counter by one, giving it a value of 2. It turns out that this is such a common thing to do, that Python provides some shorthand notation to assign new values to existing variables. The code below achieves the same result as above.

>>> counter = 1
>>> counter += 1

The += operator is a kind of “two-in-one” deal. First, it adds 1 to the value of counter (the + part), then it stores the new value in counter (the = part). A similar operator exists for decrementing variables.

>>> cost = 12.50
>>> cost -= 4
>>> cost
8.5

If you try to reassign a value to a variable that has not yet been declared, Python will give an error.

>>> ThisVariableDoesNotExist += 2
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    ThisVariableDoesNotExist += 2
NameError: name 'ThisVariableDoesNotExist' is not defined

The table below summarizes the mathematical operators that reassign values to numeric variables. Assume that num has a value of 25.

Operator Description Example Result
+= add x to variable’s value num += 10 35
-= subtract x from variable’s value num -= 20 5
*= multiply variable’s value by x num *= 3 75
/= divide variable’s value by x num /= 10 2.5
//= variable’s value becomes quotient when divided by x num //= 10 2
%= variable’s value becomes remainder when divided by x num %= 10 5
**= raise variable’s value to the exponent x num **= 2 625

2 Responses to Getting Started with Python

  1. NC says:

    Very helpful Mr. Garvin would you be able to post some sin,cos,tan work?