# Introduction to python programming

( previous, home, next )

Goals for this laboratory…

• To show you an interactive python development environment
• To show you how to use the command line of the python interpretter
• To show you how to write a script in the python language
• To show you how to run a python script
• To show you how to write a python function
• To show you how to save your work to your UDrive account

## Getting Started…

Check to see if your workstation is turned on. If it is not on, please turn it on.

If at home you have a Mac or Linux OS, you may want to familiarize yourself with the UNIX shell command line. A brief overview is given at the bottom of this page. Since we’re in a Windows computer lab is we’ll focus on that OS feature today.

The first thing that we need to do is open Spyder. Open the Main Menu, then select the Search item, and search for “spyder”. Click on the result you find.

A “welcome” window will open; it may take some time to load the first time. Once open, you should see a window similar to this …

On the left is a space where you can edit Python scripts, and the bottom right is the Python intepreter from which you can perform simple calculations or run Python scripts, and on the top is a tabbed window with tabs labelled “Variable explorer”, “File explorer”, and “Help”.

In the Python interpreter window there’s a prompt,

[Show code]
In [1]: 

(why it’s “1” is discussed below). You can navigate the file tree from this prompt. To run your scripts you need the application to be looking in the right folder for them! A few commands (that are also UNIX shell commands) will help:

• pwd: Displays the path to the directory you’re currently in. Immediately after login, this will be your “home” directory. Directories (or folders) are ways of organizing files on a computer into subsets of related files and directories. Directories are organized in a tree-structure, with “/” being the “root”, or top-most, directory. The “path” of a file is the sequence of directories needed to get to a file. The names of nested directories are seperated by a “/” (or a “" in Windows).

• cd: Changes the current directory. You can either give it:
• Use it on its own to jump straight to your home with “cd”
• a relative path: cd Folder (to a subdirectory in your current directory)
• the superdirectory above your present working directory: cd ..
• an absolute path: cd V:\PythonPractice\
• ls: list the contents of the current directory.
• list files in an absolute directory: ls "V:\Desktop\"
• list files in an relative directory: ls ..

Navigate to your UDrive account, cd V:' Remember that V: is your personal UDrive account.

• mkdir makes a new folder (i.e., directory).
• mkdir PythonPractice

Make the new folder. Then move into that directory, cd PythonPractice\.

You can save your work to this folder. Since it’s your UDrive personal directory, your work won’t get lost!

## Python

Python is a 5th-generation computer language that was created in the late 80’s by Guido van Rossum, and becoming popular around 2001 (when I learned it). It is easier to work with than many other languages, but also more flexible, having a variety of linguistic constructs not available in other languages. It gained popularity after the turn of the century as a free and flexible tool for general purpose scientific computing.

Here are some links that might be nice references tonight and in the future, but you should probably skip for right now.

### Python’s interpreter

The thing we call “Python” has a few parts. The “thing” that is python is what we call an “interpreter” (bottom right). Python’s interpreter evaluates instructions you enter at the In [ ]: prompt. In this case, the instructions expressed in the python language. Type the following commands into the python prompt and observe the results.

First, python does simple arithmetic like a calculator…

[Show code]
In [1]: 2+3
In [2]: 2 * 3
In [3]: 2 ** 3
In [4]: 7^2

Note that ** is used for exponentiation in python, while ^ is used for bit-wise negation (a boolean operation – if you don’t know what it is, do not worry, you do not need to know).

Note that the input numbers are increasing. That’s because Python remembers all inputs and outputs and stores them in an array (vector); the numbers are the vector index. You can “recall” old inputs and outputs at any time:

[Show code]
In [5]: In[4]
In [6]: Out[4]

Because we make mistakes and numbering the prompts can create confusion, I’m going to stop using them here. In the core version of the python interpretter, “>>>” is used instead to mark the prompt. From now on in the notes, I’ll use “>>>” to avoid issues with numbering each line, so remember that “>>>” is the same as “In [ * ]:” where * is an integer.

Python uses variables to store things in computer memory.

[Show code]
>>> x = 13
>>> y = x - 5
>>> print(y)

Here, we have also introduced the function print, which used to be one of the few reserved words that makes up the python language. Really, the whole language is based on only 33 words! Here is a slightly more complicated example of how print can be used with strings and inputs (answer the question, when it get’s asked).

[Show code]
>>> print("Hello, World")
>>> name = input("What is your name? ")
>>> print(name)
>>> print("Hello, %s. Nice to meet you. Would you like to play a game?"%name)

In the two cases above, x, y, and name are “variables”. Variables in python are “dynamically typed”, which means they can store many different kinds of things, and you just have to remember what kind of thing is in each one as you program. Python has a few basic variable types built in, and a simple class system for creating more of your own.

• Python has lists for sequences of objects

  >>> mylist = list(range(7))
>>> mylist
>>> mylist[0]
>>> mylist[1]
>>> mylist[-1]
>>> mylist[1:3]
>>> mylist[7]
• Python has dictionaries for pairing items.

  >>> mydict = dict()
>>> mydict['red'] = 'apple'
>>> mydict['blue'] = 'sky'
>>> mydict['red']
• Integers are different from floating-point numbers! In Python3, though, you probably won’t notice. Want to know more?

>>> u = 3
>>> v = 3.
>>> type(u)
>>> type(v)
• You can also format how things are output using the “print” command.

  >>> print("u=%d is an integer, v=%f is a float"%(u,v))

“print” works a lot like “printf” in C. “print” is especially useful because it always outputs, even when you are not interactively using the interpreter.

### Warning: not all variables work the same

In python, there is an important difference between certain kinds of variables that you might not notice at first but can cause you hours of headaches if you aren’t warned. Some variables behave like the values they are assigned, but other variables behavie like references to their objects. In math, we expect variables to behavie like their values. Variables representing numbers and other “immutable” things do behavie that way.

>>> x = 1
>>> y = x
>>> x = 3
>>> x
>>> y

As you might expect, you get out 3 for x and 1 for y. However, variables representing lists, arrays, matrics, dictionaries, and other “mutable” things actually act as references to their values rather than the values themselves.

>>> a = [1, 2]
>>> b = a
>>> a
>>> b
>>> b[0] = 3
>>> a
>>> b

Notice that you only changed list b’s initial element to 3, but the inital value of list a also changed to 3! This is because the assignment b = a copied a’s reference of the list, rather than the list itself. So a and b were both referring to the same list, and when you changed an entry using a, then variable b also sees the change. There are several ways to work around this if you want to. One is to explicitly create a new list from the old one.

>>> c = [4, 5]
>>> d = list(c)
>>> d[0] = 6
>>> c
>>> d

But, beware! If you have reference variables inside your list, like a list of lists, the your new list may give rise to the same bug! There is a special python function called deepcopy() designed to help with these issues. This bug is common for beginners working with data, arrays, and matrices. You will always need to be vigilant.

### Getting help

One of the big improvements of python over preceeding languages was the use of in-line documentation of code. This can be accessed in two easy ways.

• Inside the python interpreter, documentation on functions and variable types can be found using the function help().

  >>> help(print)
>>> x = 3
>>> help(x)
• From the standard terminal shell in Mac/Linux OS, documentation can be found using the command pydoc.

  $pydoc topics list$ pydoc keywords if
$pydoc math$ pydoc math.sin

Help commands are your friends. Use them early and often. Google or your favorite search engine too!

Because it is tedious to write out lengthy instructions every time you want to program a task, we usually save our commands to a file called a “script”. Below is a simple program that prints a table for converting between Celcius and Farenheit.

1. Select “New file” from the File menu.

2. Enter the following code into the editor window. This is what we call a script.

print('-- My Celsius-to-Farenheit table -----')
C = -20
dC = 5
while C <= 40:
F = (9.0/5)*C + 32
print(C, F)
C = C + dC
print('--------------------------------------')

The new thing in this code is that it uses a “while”-loop. A while-loop tells the computer to keep doing a particular thing as long as the condition it is given holds true. In this case, as long as the temperature in C is less than or equal to 40 degrees.

3. Save your new script as “c2f.py”. Be sure to keep track of which directory you are saving it to. Our new “PythonPractice” directory is probably the best place. The UDrive directory or Desktop are also common places. Hint: Generally, it is best not to include spaces or punctuation other than ’_‘or’.’ in file names.

4. Make a prediction about what you think will happen when you run this script.

5. Now, you can run your script. You can run the script in two ways:

• through the python interpreter,

    In [1]: run c2f.py
• by pressing the green, triangular, “run” button in the toolbar above the script. (if a dialog pops up, go with the default values at first)

Does the output match your predictions?

In most modern computer languages, functions are used regularly. A function in python is a piece of code that takes 1 or more arguments, and returns 1 or more results. This is much like the mathematical functions: in $$z=f(x,y)$$, the function $$f$$ takes in $$x$$ and $$y$$ as the arguments, and returns a result that we name $$z$$. Functions begin with the keyword def and finish when they reeach the keyword return followed by whichever variables have the results you want to return. Try the following script, which I call “c2fv2.py”

[Show code]
def CtoCF(C):
# a function to convert Celsius to Farenheit
#   takes a temperature in Celsius units as one argument
#   returns a tuple with two temps, celsius and farenheit
F = (9.0/5)*C + 32
return (C, F)

print('====')
C = -20
dC = 5
while C <= 40:
print(CtoCF(C))
C = C + dC
print('====')

## MAKE SURE THAT YOU’VE SAVED YOUR WORK TO YOUR UDrive DIRECTORY!

If you haven’t, grab your new scripts and drag them to your UDrive directory (or, if you prefer, your PASS directory). If you do not save your scripts like this, they may be lost and gone forever after you log out.

A good idea is to get a 500 Meg or larger USB stick, on which you can back up all your python work and have with you at all times! That way, you can drop into any lab or computer and work at any time if you feel like it. Of course, the down side is that you might lose it. Caveate emptor.

### Better python tools - editors, ipython and Canopy

In practice, people don’t use “python” for interactive work – just to run their programs. If you put a bunch of python commands in a file “mycmds.py” and do

    V:\PythonPractice> python c2f.py

at the Windows command prompt, or

    $python c2f.py from the standard terminal shell in Mac/Linux OS, those commands will be run, and you’ll see any outputs from print commands. Many people like me use fancy text-editors to program, which is the root of the editor wars. • vi the oldest and best (see gvim and neovim), but does not make friends easily. Pre-installed on macs and linux. • emacs is great according to some weirdos. But it isn’t the friendliest either. • Notepad++ comes from the Windows world and works smoothly. • Sublime Text is another new kid on the block. For interactive work, we usually use tools with more bells and whistles. • Spyder is a Integrated Development Environment (IDE) for python, as is Canopy. • The most commonly used interpretor for interactive work is ipython. It colorizes input, tracks input and output for future reference, allows customization, and a bunch of other useful things. Built into Spyder and Canopy. • Jupyter is an interactive web-browser based python tool. ## For Macs or Linux OS: The UNIX shell command line The first thing we need to do is get out of this gui to a terminal that shows a command line. Using the magnifying-glass “Find” button in the menu bar at the top right, search for an application called “Terminal”. Drag this to the Dock so it will be convenient. Run “Terminal”. This will open up a “terminal window”, and the program running inside the window is called a “shell”. A Shell is the generic term used in the biological sense - a simple and tough thing surrounding the important stuff. For example, your body is a shell for your mind. In this context, we are using a Unix shell. There are around 10 different unix shells that people use, and that you might want to explore once you become more familiar. Welcome to the command line. In the terminal window, there should be a line of text something like “$” This is called a command prompt. Different shells usually have different prompts. The Bourne again shell (bash) is the default shell and uses a “$” for its prompt usually. But what it is doesn’t really matter. The important thing is that there is a cursor next to it. If you start typing, that’s where things will appear. The command-line is the oldest computer interface in use, and is incredibly powerful (Before 2001, macs did not have a command-line interface. Windows dropped theirs in 1995, and brought it back in 2006), but also a little scary because of its arcane and obscure syntax. Fortunately, only a few commands are important for us right now. • pwd: Displays the path to the directory you’re currently in. Immediately after login, this will be your “home” directory. Directories (or folders) are ways of organizing files on a computer into subsets of related files and directories. Directories are organized in a tree-structure, with “/” being the “root”, or top-most, directory. The “path” of a file is the sequence of directories needed to get to a file. The names of nested directories are seperated by a “/”. Your “home” directory, where your all your files and directories are put, should look like “/Users/psuguest”. • ls: list the contents of the current directory. • Use ls -l to get a file list with lots more detail about the files. • cd: Changes the current directory. You can either give it: • Use it on its own to jump straight to your home with “cd” • a relative path: cd Desktop • the superdirectory above your present working directory: cd .. • an absolute path: cd /Users/psuguest/Desktop • touch: Creates empty files with a specific name • cd ; cd Desktop; touch myfirstfile.txt • You can do multiple commands at once by seperating them with a semicolon. • The file you’ve created should appear on the Desktop now! Check for yourself. • echo: prints out the arguments it is given • echo Hello world • echo this is my file > mysecondfile.txt • cat: lists the contents of files • cat mysecondfile.txt • rm: removes a file PERMANENTLY (CAN NOT BE UNDONE!!!) • rm myfirstfile.txt • Your file should now disappear from the Desktop • man: used to find the manual pages about a command, like man ls Unfortunately, man pages themselves are confusing. man man will tell you more about man There are many features in the shell to make your life easier – if you can think of it, somebody has probably made it possible. For example, you can use the UP ARROW to go back through your history of commands you’ve already run, so you don’t have to re-type long commands. The TAB key can be used for autocompletion often. For more information about common commands and magical incantations, see this cheat-sheet or that cheat-sheet. And remember, google is your friend. ### To open Python… At the shell prompt in the terminal, type [Show code] $ cd
$cd Desktop$ python

These commands tell the unix shell to change the current working directory to the Desktop and to run the Python interpreter. You can exit the python interpreter back to the unix shell at any time with exit() or the key combination CTRL-d (which is the character traditionally marking the end of a file).

You can also run your script from the terminal or Windows command prompt without having to use Canopy. In a new terminal window, “cd” to the directory where you saved “c2f.py” and do

    \$ python c2f.py

Or at the Windows command prompt, “cd” to the directory where you saved “c2f.py” and do

    C:\FileTree> python c2f.py
`

The output you get should be the same as what you saw in Canopy.

# Exercises

1. The proper way to test if x is one of two numbers 1 and 2 is ~python >>> x in (1, 2)~ However, sometimes beginners mistakely write things like ~python >>> x = 1 >>> x == 1 or 2 >>> x == 2 or 1 >>> x == 2 or 3 >>> 0 or 1 == x~ Explain the outputs of the code below using python’s the concepts of operator precidence and truth-value.

( previous, home, next )