edu/sts
Python
Classroom Course Manual
Updated: 08-28-2013
Table of Contents
1.0 Introduction4
1.1 About this Class4
1.2 Topics4
1.3 Required Skills4
1.4 Accessibility4
2.0 Introduction to Python 5
2.1 Introduction to Python5
2.2 Python Features5
2.3 The Python Interpreter6
2.4 Getting Help with Python6
3.0 Simple Data Types7
3.1 Variables7
3.2 Strings7
3.2.1 Exercise: Creating Strings 7
4.2 Tuples 20
4.2.1 Exercise: Creating and Indexing a
Tuple20
4.3 Dictionaries 21
4.3.1 Exercise: Creating and Modifying Dictionaries21
4.3.2 Dictionary Methods22
5.0 Functions 23
5.1 Creating User-Defined Functions
24
5.1.1 Exercise: Creating a Function 24
1.0 Introduction
1.1 About this Class
This course has been designed to give an introduction to the Python programming language. Python is
a dynamic programming language that is used in a variety of application domains. It is a language that
can be compared to Java, Perl, Ruby, and a few others. This manual will include explanatory text along
with code examples that you should be typing to follow along. Any text you should be coding will be
indicated with this font single space font.
1.2 Topics
The topics for this course will cover the basics of Python and will provide allow you to further develop
your Python skills. The topics for this course include:
Introduction to Python
Simple and Sequence Data types
Functions
Control Structures
Standard Library
Scripts
1.4 Accessibility
Python runs on many different computing platforms: Windows, Mac, and many brands of Unix. Python
can be downloaded and installed directly onto your machine from http://www.python.org/. Python
comes pre-installed on Mac machines and can be accessed through the terminal. Python version 2.7.x
Page 4
Page 5
Windows users will need to install the Python 2.7 interpreter onto their machine through the following
link: http://www.python.org/getit/. Follow the installation instructions and the Python interpreter
should install successfully on your machine.
Open up the Python Interpreter on your machine. The Python interpreter is an invaluable tool for
acclimating new users to the language. Because we are using Python as a scripting language, anything
that works in the interpreter will work in a script. Conversely, scripts can be ran entirely from the
interpreter, as the interpreter maintains state, allowing you to set variables and access them from the
interpreter using later commands.
Page 6
3.2 Strings
Strings in Python are unique because they are immutable. This means that the string cannot not
modified directly. Many mutable data structures provide methods to allow you to dynamically change
values of a given variable or data structure. With immutable data types, the developer must create a new
instance of the data type (in this case a string) and assign the variable to the new data structure. This
may sound complicated, but in practice it is very easy to create new strings by combining other strings.
Simply remember that string methods will not directly modify the contents of a variable.
Strings are defined in Python by using pairs of single quotes text or double quotes text. Multi-line
string statements are defined using pairs of 3 quotes, single or double:
This is
a Multi-line statement in
Python
Page 7
Congratulations! You have typed your first string in Python. Strings in Python are easily combined and
these combinations can be modified using comma and the plus (+) operator. Type the following in the
Python interpreter and press return after each:
print Hello, World!
print Hello + World!
The common operator will put a space between the strings and the plus (+) operator will not include
a space when the strings are combined. We have created some simple strings, but these are not very
helpful by themselves. String methods will allow us to modify variable strings.
The first two methods that will be introduced are str.upper()and str.capitalize(). Note
that str is a placeholder for the name of your string. The upper method will take the string and return all
letters as uppercase. The capitalize method will make the first letter of the string capitalized and the rest
of the letters lowercase. Note that since these are just returned values, the string itself is immutable and
will maintain the same value unless it is redefined. Lets practice using some string methods.
Page 8
Since the string s is immutable, that means the string methods are not making changes to s. They
are simply returning modified values of the string. Lets say that we want to modify the values of s
so that all the letters in the string are uppercase. Type the following code into the interpreter: s =
s.upper(). There will not be a return value for this code. Enter s and press return to see the changes
to the string.
Page 9
The first line of code just returns the original value of the string because the replace method is
case sensitive. The returned values are not permanent; the string s would need to be redefined as done
previously to retain any of the changes from the replace method.
The principles of string indexes carry over to other data types like lists, dictionaries, and tuples which will
be discussed later in this course.
Page 10
By omitting index values for this syntax, the returned value will start with the 0th index and end with
the last index of the string. Similarly, the second line of code begins with the 3rd index ending with
the last index of the string. The third line begins with the 0th index and ends with the 7th index. This is
because the j index is non-inclusive. The final line of code returns a value that starts with the 3rd index
and ends with the 7th index.
The returned results from both methods are the same. This is because we switched the index values in
both sets of brackets as well as in the format method. You can include variable or string names within
the format method for additional flexibility.
{name} pities the fool and so do {0}.format(you, name=Mr. T)
Page 11
The output from these lines of code seem to be correct. However, the last line gives us a different value
than we expected. This is because we are dividing an integer (42) by another integer (5). By dividing
an integer by another integer, the output will be another integer. The resulting integer will not contain
any decimals. The decimal values are truncated off of the result. While less concerning, multiplying
an integer by an integer will also result in an integer. We need to multiply or divide by floats to
Page 12
The resulting print statements are each a floating point number that includes a decimal. This is because
floating point numbers were used in each of the three statements. It is important to remember that to get
an output of a floating point, one of the inputs for a mathematical expression should be a floating point.
In other programming languages, such as Java, integer variables can be incremented using the ++
operand. This is not the case in Python. If you want to increment a variable in Python, you will need to
use the += value operand. The value will be added to x. Think of it as x equals itself plus the value
This will be more important once you begin to write your own Python scripts. Type the following code
to demonstrate:
x=5
print x
Page 13
Page 14
The third line of code tells Python to import all functions from the math module into the interpreter.
The * is a wildcard and represents all functions. Specific functions could be imported by replacing the
* with the function name. The advantage of importing math functions is so that you do not need to
prepend math. To the front of the function call.
Notice that in both cases of our square root calls, the outputs were floats. In general, math module
functions will return floats. This is also the case for the ceiling and floor functions. Lets try them out:
ceil(4.2)
floor(4.2)
If you did not import the entire math library with the *, you would need to type math.ceil(4.2)
and math.floor(4.2) respectively.
You can also work with trigonometry functions in both degrees and radians in Python. These functions
consider radians as the default, but its easy to switch between the two. If you recall, 1 radian is equal
to 180 degrees. The function math.sin(x) will return the sine of x radians. There are additional
functions for the other trigonometric operations. The function math.degrees(x) will convert
angle x from radians to degrees. Similarly, math.radians(x) will convert angle x from degrees
to radians. Since the math module is imported in our Python interpreter, we can omit math. from the
beginning of the functions.
sin(1)
degrees(1)
radians (180)
degrees(sin(1))
Page 15
4.1 Lists
The List is one of the most flexible data types in Python. A list in Python is a container that holds a
number of other objects in a given order. The unique aspect of lists in Python is that the data types
within the list can vary from element to element. In other programming languages, such as Java, list
elements all need to be the same data type. The additional flexibility makes Python a very powerful and
dynamic language.
We are going to create an example list, called items that contains an integer, a float, and some strings.
After we create this list, we will introduce some additional methods to demonstrate how to manipulate
lists. The syntax for creating a list is variable_name = [ 1st element, 2nd element,
3rd element, .. ]. Lets create our first list in the interpreter:
items = [1, 2.0, three, four]
print items
Note that our list includes both an integer and a float, as well as strings that were defined with and
. We can see that there is a lot of flexibility that comes along with lists. You can even nest lists inside of
lists to create 2D and 3D arrays, but that is outside the scope of this course.
Page 16
Lists can also be used like a stack by using the append method to push items on to the list and the
pop method to remove items. You can leave the argument for the pop function blank and it will remove
the item at the last index of the list. Otherwise, you can define an index for the element to be removed.
The function returns the value that is removed from the list, which could then be stored as a variable if
desired. Type the following lines of code to see how to use the pop method.
items.pop()
print items
items.pop(2)
print items
The pop method returns the value that is removed from the list. This returned value can be set to a
variable, which applies to any method that returns a value. To demonstrate, we are going to create an
integer variable that will be assigned the value of a popped listed element.
z = items.pop()
Page 17
By calling items[0] and items[2] we have returned the 0th and 2nd indexes of the list items. We can
return portions of the list by type items[i:j] as well as some other variations.
print items[1:3]
print items[0:3]
The list items contains 4 elements and is therefore indexed to 3. Remember, the j index is not
included in the return value of items[i:j]. It goes up until index j. In our case, if we wanted to
Page 18
We can see the issue that was described with the max method. The string four was considered a
higher value than the last element 5.0. Lets pop off the string element and use the max function to
return the highest value in the items list.
items.pop(2)
print max(items)
Page 19
4.2 Tuples
Another sequence data type in Python are tuples. Tuples are similar to lists in the fact that they can hold
multiple data types; however, there is one major difference. Tuples are immutable which means that
they cannot be modified. This is drastically different than lists, which have multiple methods to modify
elements.
While there isnt a way to modify this tuple, you can still return indexes just like lists. Returning
indexes for tuples uses the same syntax for returning list indexes.
print itemsFrozen[1:4]
print itemsFrozen[1:]
print itemsFrozen[:3]
print itemsFrozen[:]
Page 20
4.3 Dictionaries
A Python dictionary is a container of key-value pairs. The dictionary will store a value with an
associated key, and there can be many key-value pairs for a given dictionary. Dictionaries differ from
lists or tuples because the keys will be called to return a value rather than an index.
Dictionaries can be updated and key-value pairs can be added as well. The value of a key can be
updated by calling the key and resetting the value. This same syntax is used to create a new key-value
pair to be added to the dictionary.
nick[age] = 21
print nick[age]
nick[school] = UW-Madison
print nick[school]
print nick
Page 21
Page 22
5.0 Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reuse. As you know,
Python has a number of built-in functions like print(), but you can also create your own functions
which are called user-defined functions.
Page 23
This section of the manual was creating using the Windows version of IDLE, so your current
working directory may be different. To change your Python working directory please refer to Python
documentation available online. The current working directory is where you will want to save your
Python modules so that they can be imported by the interpreter.
We are going to create our first function inside of the new window. Before we create a new function,
there are rules that need to be followed for defining functions:
Function blocks begin with the keyword def following the function name (ex:
functionName) and parentheses ()
Any input parameters should be placed within these parentheses and separate by commas. You
can also define parameters inside of these parentheses
The code block for every function starts with a colon (:) and is indented
Page 24
print arg 1
print arg 2
Save this function as sts.py inside of the current working directory of Python. For the example outlined
in this manual, that would be inside of the C:\\Python27\ directory.
Now that the module has been saved, it is time to import the module inside of the Python interpreter and
call the function. You must use the following syntax to correctly call the function inside of the module:
moduleName.functionName(arguments). Inside of the interpreter Type the following code:
import sts
sts.text(hello, world)
You have created and ran your first user-defined function in Python. You could pass any data type into
this function such as integers, floats, arrays, etc and the function would print those arguments. The
return statement has been omitted from our function because there are no values that we need to return.
Page 25
This can be avoided by including default arguments in the function definition. This allows you to
include less parameters in the function call and the default parameter will be used. Additionally, you can
overwrite the default parameter as you would normally call the function.
print arg 1
print arg 2
Save this file once you have typed this block of code. Python only allows you to import a module
once in the interpreter, so you will need to reload the file using the reload() function.. Type
reload(sts)in the interpreter and then we can call the new function. Type these lines of code into
the interpreter after you have reloaded the module:
sts.text2(hello)
sts.text2(hello, world)
You can see that default arguments can be overwritten if needed. Otherwise default arguments help
shorten the function calls. This can be very useful with more complex functions.
Page 26
Python knows similar control structures as other programming languages. Control statements include
if statements, else-if statements, else statements, for loops, and while loops. This section will outline
examples of these control structures in Python modules.
else:
Save this file as control.py in the current working directory. You can run this module as a script by
choosing Run > Run Module in the control.py window.
The syntax for an if statement is if followed by an expression to check, such as number>15 and
ended with a colon (:). The block of code to be executed by the if statement should be indented with one
Page 27
You should see the output regarding the number four. The syntax for an else-if statement is elif
followed by an expression to check and ended with a colon (:). The block of code to be executed by the
else-if statement should be indented underneath the elif block.
Page 28
This for loop demonstrates a number of things. First, the item defined in the for loop is used to reference
the sequence of information. Each time the heading line executes, it implicitly assigns a new value to
the item (in this case i). After each execution of the heading line, the statements in the indented block
are executed, generally using the new value for the item assigned in the heading. The sequence can be a
list of items or values. To demonstrate this we will create another for loop with the range() function
in the Python interpreter:
name=nick
for i in range(len(name)):
print name[i]
<enter>
The range function generates a list containing the following values: [0,1,2,3]. Since the length of nick
is 4, the range function creates a list with 4 elements indexed at 0. The loop then prints off each element
in the variable name.
Another type of loop that is commonly used in Python is the while loop.The while loop requires
initialization of a variable. The while loop will run until a condition is met for the initialized variable,
executing lines of indented code after each iteration. The syntax for a while loop is while condition is
true: followed by lines of indented code to execute. Type the following lines of code into the Python
interpreter to create a while loop:
x = 1
while x<=10
print x
x+=1
<enter>
Page 29
This while loop prints the values 1 through 10. The += operator is used to iterate through the while
loop. One way to think of the statement x+=1 is x equals itself plus one. Python does not support the
++ operator to iterate by one like other programming languages.
This allows you to call functions from the math module within the Python interpreter or script.
Alternatively you could import all of the math functions with the following: from math import *.
This tells Python to import all of the math module functions so that you can call them directly without
prepending math. to the front of the function call. The asterisk * is a wildcard operator, similar to
searches in Google or a database. You can also import specific math functions such as from math
import pow:
Page 30
The advantage to importing specific functions is that it allows your modules to run faster. This makes a
difference in large programs; however, it will likely be negligible for your first programs.
This function produces a random number from 0.0 up to but not including 1.0. This has a number
of uses in programming. Another useful function is the uniform(a,b) which produces a random
number from a to b. The end value b may or may not be included based on rounding of the equation a
+ (b-a) * random().
random.uniform(5,50)
random.uniform(0,10)
random.uniform(-5,-1)
Page 31
The random module has a number of other functions that are further detailed in Pythons online
documentation.
Page 32
open_new(http://www.wisc.edu/sts)
Page 33
confirmation = confirmation.lower()
if confirmation == 'y':
file.write(text_answer)
file.close()
def dump_file():
file.close()
Page 34
if text_answer == None:
else:
print """
1: Enter in input
2: Write input to file
3: Dump file contents
4: exit program
"""
The first line is a comment describing this portion of the code. Comment lines are added using the #
symbol. It is always good practice to comment your code so that another user can follow your thought
process. The next line begins a while loop with while 1:, which is the same as while true:. This
means that the while loop will continue to run until a break statement is encountered. The next block of
code is an if and else statement pair that prints off the currently stored text value. The following block
of code reads the 4 options to the user. Enter the next block of code into the script.py file:
# TAKE USER INPUT
answer = int(answer)
if answer == 4:
elif answer == 1:
break
text_answer = take_input()
elif answer == 2:
Page 35
else:
write_file(text_answer)
elif answer == 3:
dump_file()
else:
continue
The first three lines of code for this block is going to take the raw input from the user, either 1, 2, 3,
4 as a string and then cast it into an integer. The remaining lines include an if statement with else-if
conditions and a final else statement to catch the remaining inputs. The first if statement checks to see if
the user entered a value of 4. If so, the break statement will close the while loop and end the script.
The next line is an else-if statement that checks if the user entered a value of 1 and calls the take_
input() function and sets the value to the text_answer variable that we initialized at the
beginning of the script. The next else-if statement checks for an input of 2. An if else statement pair
is nested inside of the elif statement to check and see that there is text to write to the file. The elif
statement will call the write_text() function and write the text_answer to a text document
named storage.txt.
The last else-if statement checks for a user input of 3. It will call the dump_file() function, which
will read the file contents and print it off in the Python interpreter. The block of code ends with an else
statement that tells the user to enter a valid value. The continue statement will tell the while loop to
continue after the else statement tells the user that they chose an invalid option.
Your final script should look like this:
Page 36
Save your script.py file and then we are ready to run the script. In the Python interpreter enter import
script and see your script run. It will prompt you for an input.
Page 37
We have successfully written to a text file saved as storage.txt. It will be saved in the current working
directory of the Python interpreter. You should be able to see this file as a basic text document:
Back in the Python interpreter, chose 3 to read back the file contents:
You have successfully run your first Python script! Enter a value of 4 into the interpreter to close the
script. Feel free to play around with the script.py.
Page 38
The following examples are shown to demonstrate some of the built in power of the python language.
The commands are meant to be run directly from a terminal, not from the python interpreter. When
using the python command, we can pass the -m option to execute a module as a script.
Page 39
Page 40
Page 41
Page 42
Page 43
Page 44
Page 45
Page 46
Page 47