# Tutorial, Part 1: First Steps with IDLE and Python

Contact: Paul Kushner, paul.kushner@utoronto.ca

This tutorial will take you through the basics of using Python with IDLE. Python is a general-purpose programming language that we will use to teach you the use of computers in physics. We will be running Python using IDLE (the "Integrated DeveLopment Environment" for Python), which is a software package that lets you test Python commands and edit and run your Python programs.

We are assuming that the Python package you will be using for your courses has been installed on your computer. If this is not the case, go to the Python installation pages and come back to this tutorial once you've installed the packages.

We use a few formatting conventions to guide you.

• Python commands and output statements are often set in bold, as in print "Hello World!".
• Blocks of code are shaded in grey boxes like this:
print "Hello World!"
a = 2
b = 3
print "a times b is", a * b
• Code written in these boxes includes colored highlighting for different parts of the Python language (commands, variables, comments, etc.). If you don't understand the color highlighting, don't worry about it for now.
• Activities and exercises for you to try are labelled in blue font as Activity 1, Activity 2, etc.

## 1. Starting IDLE

During a typical IDLE session, you will try Python commands interactively, and edit and run Python programs. In these activities, we will start an IDLE session and run a couple of simple scripts. These scripts are also used in the Installing Python documentation.

Remark about opening .py files directly: We do not recommend opening python files ending with .py by double clicking them. Instead, open the scripts from within your IDLE session, using File → Open. This is because the behaviour you get can be unexpected, although it won't do any harm.

Activity 1: Now do the following:

• If you are running Windows, you will be starting IDLE from the Python XY package. From Start Menu, open IDLE as follows:
Start → All Programs → Python 2.7 → IDLE (Python GUI)
The typical result will be a window labelled "Python Shell" which w ill look like the following:  windows-pythonshell.png

If you are running MacOS, from the Applications folder, open IDLE as follows:
Applications → Python 2.7 → IDLE will open a "Python Shell" which will look like the following:
 mac-pythonshell.png

There are other ways of running Python, but these are beyond the scope of our current documentation.
• We will try a couple of scripts to get you familiar with how to run them. The scripts can be found in the examples folder, which you can download hereas a zip file.
• Download the examples folder, unzip it, and look at the list of examples in the folder.
• In the IDLE program, using File → Open in Windows or Mac OS, go to the examples folder. Open the file called "bounce", which might show up as bounce or as bounce.py in the directory listing.
• In the menu, select Run Run Module. (The shortcut for this is F5.) This should produce an animation of a bouncing ball (see below).
 visual_snapshot.jpg

You are looking at the scene from the perspective of a virtual camera; you can move the camera around the scene with your mouse. You can rotate the camera to different orientations or you can zoom and pan. The mouse controls on Windows and Mac systems can be different.
• To rotate the camera, typically you hold down the right mouse button and move the mouse. On Mac systems you might have to press the command key and move the mouse. Now try rotating the camera.
• To zoom and pan, typically you hold down the middle button and move the mouse. On Mac systems you might have to hold the left and right buttons, or push the option key, and move the mouse. Now try zooming and panning.
• Close the animation window. We are now ready to move onto the next example.
• The next example plots some data. In the examples folder, find the file called "matplotlib_example.py", which might show up as matplotlib_example or matplotlib_example.py.
• Select Run Module (shortcut F5). (You might need to wait for a minute or more before anything happens.) This should produce a plot of global mean temperature at the Earth's surface, as a function of year for several decades (see screenshot below). This plot uses data from the NASA GISS website.
 matplotlib_snapshot.jpg
• Now, feel free to open and run any of the scripts in the examples folder (e.g. gas.py and stars.py). You can also change them by editing them, saving them, and running them (IDLE will only run a script that has been saved to disk). Tinkering with scripts is a great learning approach; even if you only understand part of what's going on in the scripts, you can have fun changing them and seeing what the result is.
• When you're done, quit IDLE and go on to the next section.

## 2. Using Python Interactively

A "shell" is a computer program that lets you interact with a program or an operating system. IDLE lets you open a "Python shell" where you can enter commands for Python to process (or "interpret"). In this section, we will use the Python shell to do some calculations interactively.

Activity 2a: Now do the following:

• Using the instructions above, open the IDLE program (Windows: Start → All Programs → Python 2.7 → IDLE (Python GUI). Mac: Applications → Python 2.7 → IDLE)
• If you see a window labelled Untitlted then from the Run menu choose Run Python Shell.
• Now you should see a window labelled "Python Shell".
• Your session window should look something like this:

After some technical info, there is a prompt, ">>>".
• Now, at the prompt type
>>> print "Hello Toronto!"

and press return.
You will see
>>> print "Hello Toronto!"
Hello Toronto!

(Your IDLE session will color the text in different fonts to guide you.)

What just happened? The interpreter was waiting for a command, which you issued by pressing the return key after you typed the text. The interpreter read the command, which asked it to print out Hello Toronto! It didn't see any problems with what you typed, so it responded by following your command.

The "Hello Toronto!" that appeared in this example is known as a string, which is typically a sequence of characters enclosed by quotation marks (single quotes or double quotes). Strings typically represent information (data, warning messages, etc.) that are meant to be readable. For more advanced information about strings and print statements see Fun with Strings.

Activity 2b: Now what if you made a mistake? Let's see what happens by doing the following:

• Type
>>> print "Hello Toronto!

without the second quote " and press return. You should see
>>> print "Hello Toronto!
SyntaxError: EOL while scanning single-quoted string

The interpreter complained (gave a Syntax Error) when it found the end of the command line (EOL) without finding the end of your string with the closing quotation mark. So even though it might have been clear enough to you what was wanted, it wasn't clear to the interpreter and so it didn't print out your command. But notice also --- and this is important --- that your mistake had no other consequences. It didn't destroy Python, or burn out the motherboard of your computer. So don't worry about making mistakes in programming. It just comes with the territory.

Activity 3: Now let's do a simple calculation:

• At the prompt, type
>>> 5.0*2.0

and press return.
You will see
>>> 5.0*2.0
10.0

Activity 3 shows how the Python shell can be used as a calculator; you can scroll up and down in the shell session to look at the calculations you've done. The * is called an operator and there are many of them. We can do standard arithmetic, and a lot more. For example

>>> 5.0/2.0
2.5

The **operator raises a number to a given power:

>>> 2.0**3.0
8.0
>>>4.0**0.5
2.0

The latter example took the square root of 4. You can use parentheses to group operations together:

>>> (4.0**0.5)**0.5
1.4142135623730951

You need to be careful with the order of operations you input, which follow Python's "precedence rules". For example,

>>>2.0 + 3.0 * 5.0
17

calculates 3.0*5.0 first and then adds 2.0. It is a good idea to use parentheses to make things clearer, as the following examples show:

>>>2.0 + (3.0 * 5.0)
17.0
>>>(2.0 + 3.0) * 5.0
25.0

A number like 2.5 with a decimal is known as a floating point number or float, and a number like 2 without a decimal is an integer. When Python divides two integers, it rounds down to the nearest integer, so for example 5/2 will give you the result 2.

Now suppose you wanted to find out the remainder of the quotient of the 13 and 2, which is 1. To get this, you use the modulo operator,%, which prints the remainder. Here are a few examples of using the mod operator.

>>>3 % 2
1
>>>3.0 % 2.0
1.0
>>>5.9 % 2.3
1.3000000000000007


In the last line, the computer calculated its best guess on the remainder, to within the computer's numerical accuracy. Your computer may give slightly different results --- try it out.

Activity 4: To test this behaviour do the following:

• Compare the results of the following quotients. Type them one at a time and look at the results.
>>> 8.0/4.0
>>> 8/4
>>> 5.0/2.0
>>> 5./2.
>>> 5./2
>>> 5/2
>>> 1./2.
>>> 1/2
>>> (3.0**2)/(1.5**0.5)
• Then, repeat this, but replace the division "/" operator with the mod operator "%".
• Notice the following:
• The quotient of two floating point numbers is always a floating point number, and the quotient of two integers is an integer.
• The trailing zero after the decimal point can be omitted, so that 5. is equivalent to 5.0.
• The quotient of a floating point number and an integer is a floating point number.

Activity 5: Here's another exercise:

• Predict the result of the following calculation
>>> (2.0/4.0)**(1/2)-(13.0/14.0)**(5/2-7/3)

and check your prediction by typing the command.

Now, let's write a little code to calculate a formula in physics. From first year mechanics, we know that an object projected upward with speed v will reach a height, $$h = {v^2 \over 2g}$$,

in the absence of air resistance. Suppose you throw a ball with a vertical component of velocity of 12.5 m/s. The following calculates the height reached:

>>> 12.5**2/(2*9.8)
7.9719387755102034

So the ball rises about 8 meters.

### Introducing Variables and Assignment Statements

Another person looking at the statement >>> 12.5**2/(2*9.8) in the previous example would have no idea what the calculation means. To produce clear work that anyone can understand, we need to use variables.

Activity 6: Let's redo the previous example using variables.

• Type the following commands one at a time, pressing return after each command:
>>> v=12.5
>>> g=9.8
>>> h=v**2/(2*g)
>>> h

In these expressions, the interpreter assigns a value to v and g, and assigns h a value based on the values of v and g. The formula for h and the dependence on the variables are clearer now. The last line printed the value of h:

>>> h
7.9719387755102034

The variable h in this example refers to a specific number and not a symbolic formula. As a result, if you change v or g, the value of h won't change, even if we originally set h by a formula involving v and g. To see what we mean, try typing the following:

>>> v = 15
>>> h
7.9719387755102034

The point here is that h stays the same, even though v has been changed. To update h to reflect the new v, we need to repeat the formula:

>>> h = v**2/(2*g)
>>> print "The height of the ball h =", h
The height of the ball h = 11.479591836734693

So for a starting velocity of 15 m/s, the ball rises about 11.5 m.

The statement h = v**2/(2*g) is an assignment statement, and we will stop for a bit and think about what it means. In this statement, the equal sign "=" is telling the Python interpreter to take the numerical value of the calculation v**2/(2*g) and assign it to the variable h. Until we write another assignment statement with h on the left hand side, the value of h does not change.

Assignment statements can be chained together to update a variable without creating a new variable. For example, on my birthday, my age is increased by one year. The following commands would be good for marking my birthday.

>>> age = 42
>>> print "Your current age is", age
Your current age is 42
>>> age = age + 1
>>> print "Happy Birthday! Your new age is", age
Happy Birthday! Your new age is 43

A short form for the construction age = age + 1 is age +=1. Similarly,

• a = a - 1 is equivalent to a -= 1,
• a = 2* a is equivalent to a *= 2,
• a = a/2 is equivalent to a /= 2.

Activity 7: Now do the following:

• The activity of radiatioactive decay for a given sample (Knight, Second Edition, Chapter 43) is given by
$$R(t) = R_0 ({1 \over 2})^{(t/t_h)}$$, where $$R_0$$ is activity at $$t = 0$$ and $$t_h$$ is the half life.
• You can use this formula to show that
$$R(t + \Delta t) = R(t) \cdot ({1 \over 2})^{\Delta t/t_h}$$.

[Don't worry if you don't understand these expressions completely. Just take them as given.]
• The half life for Cesium-137 is 30 years (Knight, Second Edition, Example 43.3). Given an initial activity of 5.0µCi (microcurie), write some code that will print the activity in microcuries every 10 years for four or five decades.
• One way to approach this problem is to first define a variable fac that represents the constant $${1 \over 2}^{\Delta t / t_h}$$

that appeared in the half-life equation. Notice that this constant is independent of time t but depends on the elapsed time ∆t. Then define a variable r that represents the initial activity. Then the assignment statement r = r * fac or r *= fac updates the activity to its value at time ∆t. Repeating this assignment statement will give you the activity every ∆t.
• A sample session in which we solve this problem can be found here.

## 3. Using Python Scripts

We have been using Python interactively for these first quick answers and examples. Interactive shell sessions are nice for trying a couple of commands in a row. But if you need to chain together a sequence of several commands, as in the last exercise, it is much more efficient to save them to a file and use IDLE to run the file. A set of Python commands in a file is called a script. Like a movie script for an actor, the Python script tells the Python interpreter what to do and in what order to do it.

First, we'll introduce comments, which are lines of text that are ignored by the Python interpreter but that are included to help explain your code to others and to remind yourself what your code is intended to do. Good code writing requires good comments. Comments in Python start with a # sign. Any text following the # sign is ignored by the interpreter. For example, if you cut and paste the following command into the Python shell, the text after the this print statement will not be printed.

print "This is a print statement." #This comment will not be printed.

(Notice that the color highlighting in the code block makes comments appear grayed out. This is the type convention followed by the wiki software we are using; some people find the comments hard to read as a result.)

Activity 8: Now we will save some commands to a file and run the file as a Python script.

• First, open a new file from within IDLE, by going to the file menu and pointing to File → New.
• We will redo our previous projectile example as a script. In the script window, enter the following commands by either cut-and-pasting or typing:
#Initial vertical velocity . . . A comment to start things off!
v = 15.0
#Gravity
g = 9.8
# height formula
h = v**2/(2*g)
# print result
print "If v = ", v, " and g = ", g, " then h = ", h,"."
• [Again, the color highlighting in the code box is intended to guide you. You can cut and paste this code into a script without worrying about the colors.]
• Now, save the script to a location of your choice. Call it vgh.py, or some other name you prefer, as long as it includes the .py extension. IDLE will not provide you with the .py extension automatically.
• (We repeat: It is important that you save your code with the extension .py.)
• Then, run the script. There are two ways to do this:
1. You can go to the Run menu and select Run → Run Module or
2. You can type F5.
• This will run the module and should produce the following output in the interpreter:
================================RESTART================================
>>> If v = 15.0 and g = 9.8 then h = 11.4795918367.

Your session might look something like this, with the file window on the left and the shell on the right.
In the file window on the left, we've entered the commands and you can see that IDLE has colored the text using its syntax highlighting. It does this in both the shell and file windows.)

The script consists of the set of commands you have already run interactively. We have added comments that start with # to help document the code.

When you selected Run Module or typed F5, several things happened. Run Module or F5 is a command that asks IDLE to translate (compile) the code into a form the computer can understand, load the translated code into the computer memory, and run the commands in the script one at a time in the order they are written. You as a user should understand the following about Run Module or F5 in IDLE:
1. IDLE first restarts the Python interpreter (as indicated by the RESTART message). This clears out all previous settings and memory usage.
2. It then runs each separate line in your script as a command. That is, the script executes all the command sequentially, in the order that they are written.
3. It skips every comment line in the script.
4. Once it is finished, it returns a prompt, >>>. This means that is now waiting for further instructions. You can now go ahead and type additional commands interactively.

Activity 9: Create and run another script for practice.

• Redo Activity 7, using a script instead of interactive commands. At each time increment ∆t, print the current time as well as the activity.
• A sample script can be found here
and sample output can be found here
.

Mistakes, Bugs, Errors, Warnings: It is sad but true that most of your time in programming will be spent debugging --- finding and fixing coding errors. Strategies for debugging are covered here in the Python Reference, but this is a good point to say something about IDLE's debugging hints. You will find that when a code contains errors that are obvious, IDLE will try to inform you that it sees the problem and will try to identify where the problem might be. For example, in the following, the first line introduces a syntax error and the second tries to print the value of a variable that has not been defined.

Activity 10: Do the following

• Enter the following commands in the Python shell, one at a time.
a = 2
b = 3.0
ab = a b
print my_new_variable #my_new_variable has never been defined
• Do you see where the syntax error is? Do you see another problem? What did IDLE do to point out the problems in each case?
• Now, copy and paste the commands above into a script, and run the script.

Before we end Part 1, we would like to point out that there are other ways of running Python and other Integrated Development Environments (IDEs) for Python programming. You can explore these as you get more comfortable with Python, but IDLE is sufficient for our purposes.

## 4. Summary and Conclusions

This section started out with an introduction on starting IDLE for Python and running programs from it. Using IDLE, inputting and using the shell was also demonstrated. By now you should surely be comfortable with both IDLE and the python shell and the basic operations they can be used for. This includes being able to use the operators +, -, /, *, etc... within the shell. The operator = is a powerful tool, it can be used in Python to both assign and modify variables, which in turn can be used to clarify formulas. Comments were also covered in this section and are a vital part of programming in any language. It is considered proper form to put a comment beside any confusing piece of code you may write. This helps both you and anyone else reading the code if ever a part of code needs to be reused and its purpose is forgotten. The final section of this part of the tutorial covered making and saving .py programs outside of the shell. If you are not comfortable doing this go back and reread that part of the tutorial. Making and using .py files will be necessary to complete 90% of the remaining portion of this tutorial. Here are some questions about the all the material covered in this section. You should be able to complete all of them. If not, go and seek help.