Вы находитесь на странице: 1из 47



Classroom Course Manual

Updated: 08-28-2013

Software Training for Students (STS)

University of Wisconsin-Madison

About Software Training for Students

STS is part of the Division of Information Technology (DoIT), which coordinates computing,
networking, telephone, video and other information technology services at UW-Madison.
For more information regarding DoIT, visit www.doit.wisc.edu. For more information on
the Software Training for Students (STS) program, visit our website at www.wisc.edu/sts,
email sts@doit.wisc.edu, call (608) 265-6699, or call (608) 265-4615.

University of Wisconsin Board of Regents

This manual and any accompanying files were developed for use by current students at the
University of Wisconsin-Madison. Many STS materials were developed in partnership with the
University Information Technology Services (UITS) IT Training program at Indiana University.
All rights reserved.
The names of software products referred to in these materials are claimed as trademarks of their
respective companies or trademark holder.
If you are not a current member of the UW-Madison community and would like to use STS
materials for self-study or to teach others, please contact sts@doit.wisc.edu or call
(608) 265-6699.

STS Manual Template

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

3.3 String Methods8


Exercise: Using String Methods  9

Exercise: Additional String Methods 9
String Indexes10
Exercise: String Indexes10
Exercise: The Format String Method11

3.4 Numbers and Simple Math 12

3.4.1 Working with Numbers12
3.4.2 Additional Mathematical Operands 13

3.5 Using Math Module Functions 14

3.5.1 Calling Math Module Functions14

4.0 Sequence Data Types 16

4.1 Lists 16
4.1.1 Exercise: List Methods17
4.1.2 Exercise: List Indexes18
4.1.3 Exercise: Additional List Methods19

4.2 Tuples 20
4.2.1 Exercise: Creating and Indexing a


4.3 Dictionaries 21
4.3.1 Exercise: Creating and Modifying Dictionaries21
4.3.2 Dictionary Methods22

4.4 Checking and Casting Data Types

4.4.1 Exercise: Using the Type Method22
4.4.2 Exercise: Casting Data Types23

5.0 Functions 23
5.1 Creating User-Defined Functions
5.1.1 Exercise: Creating a Function 24

5.2 Functions with Default Arguments

5.2.1 Exercise: Creating a Function with a
Default Parameter26

6.0 Control Structures 27

6.1 If and Else Statements 27
6.1.1 Exercise: Creating an If Statement27

6.2 For and While Loops  28

7.0 Standard Library 30
7.1 The Math Module 30
7.2 The Random Module 31
7.3 The Tkinter Module 32
8.0 Creating a Functional Script 33
9.0 Power of Python (working title) 39
9.1 Useful Snippets 39
9.1 Fun snippets 39

STS Manual Template

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
Control Structures
Standard Library

1.3 Required Skills

While previous programming experience is not required, it is helpful, and basic scripting experience is
recommended. An understanding of mathematical operations will be required for this course. Previously
experience with logical expressions will also be helpful for this course.

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

Software Training for Students (STS)

STS Manual Template

is the industry standard and is recommended for new users. Python 3 is also available, but is drastically
different from Python 2.7.x and has less learning material available. The website also contains many
tutorials to help supplement the material from this course.

2.0 Introduction to Python

2.1 Introduction to Python
Python is a clear and powerful object-oriented programming (OOP) language, comparable in terms of
functionality to Perl, Ruby, Scheme, and Java. Python does differentiate itself from these programs with
an elegant syntax, which makes the programs and scripts you write easier to read and debug. Python
uses a syntax which borrows from both procedural C-like languages and functional languages. The
Python language is very easy-to-use that makes it simple to get your program working.

2.2 Python Features

Pythons standard library supports many common programming tasks, such as connecting to web
servers, searching text with regular expressions, reading and modifying files. This makes it very quick
and easy to do tasks that would take many more lines of code in other programming languages. Python
can also be embedded into an application to provide a programmable interface.
Python supports nearly all the programming paradigms. A developer can use Python as an OOP
language with classes and multiple inheritance. Unlike Java, Python does not force OOP practices,
allowing the developer to use functional, procedural, or OOP paradigms, mixing and matching different
practices when appropriate. Additionally, code can be grouped into modules and packages. This allows
the code of one Python program to be grouped and used in another Python program. This allows users
to quickly develop dynamic programs.
Pythons data types are strong and dynamically typed, which means that variables are typeless. It is easy
to change from one type to another. For example, it is easy to change a variable from an integer to a
double to a string.
The main drawback to this diverse set of features is runtime speed. Although Python can be compiled
into native machine code (through a somewhat arduous process) it is typically written as a script, and
interpreted at runtime which typically comes with a performance overhead. Knowing this, the creators
of the language made it very easy to write portions of a program in a compiled language (such as C
or C++) and integrate them into your Python script. This allows you to reap all the benefits of Python,
without compromising speed and performance on important tasks.
Ultimately, Python is a great language for new programmers and experience programmers alike.
Experienced programmers will love the standard library and new programmers will love how easy the

Software Training for Students (STS)

Page 5

STS Manual Template

syntax is to learn. The shortened development time increases productivity, reduces costs (both in initial
development and maintenance), while providing the developer with a much more pleasant and less
stressful experience.

2.3 The Python Interpreter

The Python interpreter is a shell that allows user to enter code line by line for testing or trial and
error. The interpreter provides many options including being able to open a new script window where
complete Python programs can be written in a built in Integrated Development Environment (IDE).
As previously mentioned, Python comes pre-installed on most Mac machines. To open the Python

Mac Finder Applications Spotlight Search for Terminal Type python
type idle

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.

2.4 Getting Help with Python

Python has a very detailed help menu that can be entered through the Python Interpreter. Once you have
the Python Interpreter opened, type the following:
This will enter you into the Python help utility. You can enter any module, keyword or topic into this
utility to get more information. For example, to get more information about strings you would type str
inside of the help module. Quit the help utility by typing quit.
You can enter arguments into the help utility call to get information more quickly. Type help(str)
inside of the Python interpreter to get information about strings. This will bring up the help menu for
strings and then you will need to quit the utility to continue working in the interpreter.

Page 6

Software Training for Students (STS)

STS Manual Template

3.0 Simple Data Types

3.1 Variables
As in other programming languages, variables are symbols or names that stand for a specific value.
Variables can be many different types in Python: numbers, string, list, tuple and dictionary.
There are some naming conventions that need to be followed when naming a Python variable. Variable
names cannot contain punctuation characters such as @, $, and %, with the exception of the underscore
character. Python is a case sensitive language, so two variables named Buckybadger and buckybadger
would be considered different variables. Most programmers follow the camelCase naming convention
where the first letter of each word is the name is capitalized except for the first word. Variables may
contain numbers but must start with either a letter or an underscore.
Variables follow this structure: variableName = value. The text entered after the equals sign
depends on the type of variable you are using. To demonstrate, we are going to start by creating some
string variables.

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

3.2.1 Exercise: Creating Strings

We will begin by using the Python command (and therefore a reserved word) print to give us output
for the strings that are going to be entered in the interpreter. Lets print a basic string! In the Python

Software Training for Students (STS)

Page 7

STS Manual Template

Interpreter, type print Hello World! and press return. You should see the interpreter respond
back with your string.

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.

3.3 String Methods

Python has a series of built-in methods that allow users to return manipulated string values. There
are many more methods built into Python that are used on other data types. A Method is considered a
subroutine or a procedure that is associated with a given type and performs its function when called. In
many other languages these are referred to as member functions or simply functions.
Lets setup our first variable and given it a string value so that we can use some of Pythons string
methods. Type s = Hello World! into the Python and press return. This will give a variable, s,
the value of Hello World!.

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

Software Training for Students (STS)

STS Manual Template

3.3.1 Exercise: Using String Methods

You have already defined the string s which we will be applying the string methods to. Type out the
following lines of code, pressing return after each and view the outputs:
Note that the return values from Python are the modified string values. The return values are not
permanent changes to the string s. Type s into the interpreter and press return to see that the string
still has the value of Hello World!.

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.

3.3.2 Exercise: Additional String Methods

Being able to search for information or data through string values can be a very useful procedure in
Python and other programming languages. The str.find(value) method will return a positive
value if the string contains the valuing being searched for; otherwise the method will return -1. The
value or argument within the find method is case sensitive. To test this, Type the following lines of
code into the interpreter:

Software Training for Students (STS)

Page 9

STS Manual Template

Another useful method is replace. This method will take two string values as inputs. It will find the
first value, if it exists, and return the string with the second value in place of the first value. The replace
method is also case sensitive like the find method. If the first value does not exist in the string, the
replace method will just return the original string. Type out the following code in the Python interpreter
to demonstrate:

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.

3.3.3 String Indexes

The positive value returned by the find method indicates the lowest index in the string in which the value
has been found. String indexes begin with 0, so the returned value of 1 indicates that ELL is found in
the second index of the String s.
The string s current has a value of HELLO WORLD!. The first index 0 has a value H. The index values
for the string s are as follows:

The principles of string indexes carry over to other data types like lists, dictionaries, and tuples which will
be discussed later in this course.

3.3.4 Exercise: String Indexes

You can return partial values of a string by searching through its indexes by using str[i: j] where i
and j are indexes. The j index is non-inclusive meaning that the returned value will be up until the value
of j. Type out the following code to demonstrate:

Page 10

Software Training for Students (STS)

STS Manual Template


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.

3.3.5 Exercise: The Format String Method

The format method allows for string manipulation. It can insert specific values into placeholders in a
string that are indicated by {value} (curly brackets). The value inside of the curly brackets can be blank,
ordered numbers or names of specific strings. Lets practice this to get a better understanding of how
this Method works. Type the following code and press return:
{} pity the {}.format(I,fool)
The format method places the strings I and fool sequentially into the string. If we were to switch
the order of I and fool inside of the format method, the string would read fool pity the
I. This can be accomplished by using index values inside of the { } brackets. The first value in the
format method is indexed 0, the second value is indexed 1, and so on. Type the following code to
demonstrate this:
{0} pity the {1}.format('I', 'fool')
{1} pity the {0}.format('fool', 'I')

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)

Software Training for Students (STS)

Page 11

STS Manual Template

The string you is in the 0 index of the format, therefore it displays inside of the {0} brackets in our
string. Any indexed string values inside of the format method must come before any strings that have a
temporary variable name given to them. This is the reason that name=Mr. T needs to come after
you inside of format(you,name=Mr. T).

3.4 Numbers and Simple Math

Working with numbers and basic math functions is very similar to other programming languages.
Python also has a built-in math library which makes calling math functions very efficient and easy.

3.4.1 Working with Numbers

Before we can dive into working with numbers in Python, we should define the different types of
number object types that are available in Python. The four types are integers, long integers, floating
points, and complex numbers. While long integers and complex numbers have important programming
applications, this course is going to focus on integers and floating points. Integers are whole numbers
that do not have any decimals. Floating points or floats contain decimal points. As mentioned earlier in
this class, Python variables are typeless so it is easy to change from one number type to another but the
output of math functions are dependent on the inputs data types. Keep in mind that the resource usage
of a floating point number is much greater than an integer.
Python follows normal mathematical operations. Were going to be using print to display some
outputs of using numbers. Type out of the following four lines of code to get some outputs:
print 42
print 40 + 2
print 42 * 2
print 42 / 5

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

Software Training for Students (STS)

STS Manual Template

maintain decimals. The same applies for addition and subtraction. Type the following lines of code to
demonstrate this:
print 42.0 * 5
print 42.0 / 5
print 42 / 5.0

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.

3.4.2 Additional Mathematical Operands

Python has a few other mathematical operations that are built-in: absolute value and power. The
absolute value operation is called by type abs(x). Absolute value will return the value of x without
regard to the sign. The power operation is called by pow(x,y) and will return the value of x to the
power y. The power operation can also be called by x**y. Lets demonstrate:
print abs(-4)
print pow(2,5)
print 2**5

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:
print x

Software Training for Students (STS)

Page 13

STS Manual Template

print x
print x (modify pictures to include print?)

3.5 Using Math Module Functions

Python has access to a large library (or module) that contains many complex math functions. These
functions are defined in the C standard and require real numbers as inputs. There are separate function
calls for inputs that use complex numbers.
The math module needs to be imported into Python before the functions can be called. The math
module can be imported by typing import math into the Python interpreter. This will require math.
to be appended to the front of the function call. By adding from math import * to the interpreter,
the entire math library can be called without adding math. to the beginning of a function call.

3.5.1 Calling Math Module Functions

Three math functions that could be considered useful are square root, floor, and ceiling. The square
root function takes the square root of the indicated value. The floor function will round a float down to
the closest integer, while still retaining the float type. The ceiling function will round a float up to the
closest integer. Lets call the square root function by typing the following code:
import math
from math import *

Page 14

Software Training for Students (STS)

STS Manual Template

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:
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.
radians (180)

Software Training for Students (STS)

Page 15

STS Manual Template

Python also has built in values for reserved math numbers: math.pi and math.e. Try it out:

4.0 Sequence Data Types

Python, like many programming languages, has additional data types that are more suitable for
sequences of information. In Python, these data types are defined as lists, tuples, and dictionaries.

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

Software Training for Students (STS)

STS Manual Template

4.1.1 Exercise: List Methods

Lists can be modified by using the append and insert methods. The append method will add an
element to the end of the list, which will have the last index. The insert method will insert an element
into a given index and then push the remaining list elements over to the right.
print items
items.insert(4, 5.0)
print items

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.
print items
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()

Software Training for Students (STS)

Page 17

STS Manual Template

print z
print items

4.1.2 Exercise: List Indexes

The previous section of the course discussed indexes related to strings. We demonstrated that you can
return particular indexes of a string by using str[i] or str[i:j] where i is the starting index and
j is the non-inclusive ending index. This same syntax applies to lists. Lets demonstrate by first adding z
back to the end of our list and then returning some indexes.
print items
print items[0]
print items[2]

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

Software Training for Students (STS)

STS Manual Template

include the last element in the list we would leave the j index blank to go all the way to the end of the
list. This same syntax applies for the beginning of the list. You can leave the i index blank instead of
including the 0th index to return values beginning from the start of the list.
print items[1:]
print items[:3]
print items[:]

4.1.3 Exercise: Additional List Methods

Three additional methods that are useful are the max, min, and length (len) methods. The length
method will return the number of elements in the list. Remember, the last indexed element in the list
will be 1 less than the length of the list. The max method will return the highest value within the list.
This becomes tricky with string elements inside of a list; strings are considered to be a higher value than
number elements. Similarly, the min method will return the lowest valued element in the list.
print len(items)
print max(items)
print min(items)

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.
print max(items)

Software Training for Students (STS)

Page 19

STS Manual Template

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

4.2.1 Exercise: Creating and Indexing a Tuple

Tuples are defined using open brackets ( ) instead of square brackets [ ] which are used for lists. Tuples
are essentially frozen lists; they are immutable and cannot be modified. Tuples are usually used when it
is known that the values will not change throughout a program or a script. Tuples are faster to process
than lists, which makes them preferred in large programs if they do not need to be modified.
itemsFrozen = (1, 2.0, three, 4, five)
print itemsFrozen

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

Software Training for Students (STS)

STS Manual Template

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.

4.3.1 Exercise: Creating and Modifying Dictionaries

Dictionaries are initialized by using curly brackets { } with a key:value syntax. The keys for
dictionaries are strings, so either single or double quotes must be included around the key. Quotes must
also be included on string values, but not for integers or floats. Lets create a sample dictionary to store
information about a student:
nick = {name:nick, major:Computer Science, age:20}
print nick
print nick[age]

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

Software Training for Students (STS)

Page 21

STS Manual Template

Remove key-value pairs from a dictionary is not the same as removing elements from a list. Dictionary
key-value pairs require use of the delete (del) method.
del nick[school]
print nick

4.3.2 Dictionary Methods

There are some useful methods that will return dictionary information. The first method is the has_
key method. This method will return a true or false value depending on if the dictionary has the
indicated key. The keys method returns a list of the dictionarys keys. Similarly, the values method
returns a list of the dictionarys values.

4.4 Checking and Casting Data Types

Checking and casting data types in Python can be done using some built in methods. In this example,
the type method will be used to return an input type.

4.4.1 Exercise: Using the Type Method

The type method will return the variable or parameter input type. To practice, we will use some integers
and previous variables that were defined inside of the Python interpreter.

Page 22

Software Training for Students (STS)

STS Manual Template


4.4.2 Exercise: Casting Data Types

There are instances that you could come across while writing programs that would require you to
change one data type to another. For example, from an integer to a float or a float to a string. This can be
done using specific methods. Some example ones include int, float, and str. It should be noted that there
are some data type conversion limits. For example, you cannot cast a string into an integer but you can
cast an integer into a string.

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.

Software Training for Students (STS)

Page 23

STS Manual Template

5.1 Creating User-Defined Functions

Functions can be stored in separate modules as Python files (file extension .py). This allows a user to
import the modules into the Python interpreter and call the functions. This helps make your programs
modular and easier to code/debug. We are going to create two simple functions in a module and import
them into the interpreter.
Python has a large number of built-in functions. You already have experience calling these functions
such as print(arg), max(arg), and len(arg). The text arg is a placeholder for the function
argument. An argument is a parameter that is passed to the function and is referred to a piece of data
while the function executes.
You have also looked at some functions that did not require any arguments. These functions included
.pop() when the last item of a list was popped off. Functions can be defined to include arguments or
not to include arguments, it just depends on how the functions are being used. For our example, we will
be using two functions that include arguments.

5.1.1 Exercise: Creating a Function

The function that we will create is going to be saved in a separate module and imported from the
interpreter. To open a new window in the interpreter navigate to File > New Window. The second step is
to get the current working directory to know where to save your module files so that it can be imported
by the interpreter. Inside of the Python interpreter type the following:
import os

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

Software Training for Students (STS)

STS Manual Template

The statement return [expression] exits a function, optionally passing back a value to the caller.
A return statement with no arguments is the same as return None.
Inside of the new window type the following code to create your first function:

def text(arg1, arg2):

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.

5.2 Functions with Default Arguments

Function arguments must be included when you call them in the interpreter. If you forgot to include the
second argument in the sts.text function you would receive the following error:

Software Training for Students (STS)

Page 25

STS Manual Template

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.

5.2.1 Exercise: Creating a Function with a Default Parameter

Open the sts.py module if you have closed it. In the file type the following code below the other
function block:
def text2(arg1, arg2=default):

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, 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

Software Training for Students (STS)

6.0 Control Structures

STS Manual Template

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.

6.1 If and Else Statements

The if and else statements are the most famous control structures statements in programming languages.
An if statement will check to see if a statement is true and then execute the code block. If the statement
is not true, the if statement will evaluate to false and not execute the code block. The else statement is
used as a catch and will execute a code block if the if statement evaluates to false. An else statement
is an optional part of an if statement.

6.1.1 Exercise: Creating an If Statement

The syntax for an if statement is fairly simple. Open a new window and Type the following code
block to demonstrate:
number =4
if number >15:

print the number is larger than 15


print the number is less than 15

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

Software Training for Students (STS)

Page 27

STS Manual Template

tab underneath the if statement. The else statement follows a similar structure but does not require the
conditional expression to check.
From the output of the interpreter we see that it tells us that our number is less than 15. We expected
this result. We are going to add an else-if statement to our control script. Else-if statements allow you
to check for additional conditions to execute code blocks within the same statement. For example, lets
add an else-if statement that checks if our number is equal to four. Inside of the control.py file, add the
following block of code between the if and else statement and rerun the module:
elif number==4:

print the number is 4

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.

6.2 For and While Loops

A loop is a sequence of instructions that is continually repeated until a certain condition is reached.
These loops come in the form of for and while loops in Python. For loops and while loops are very
common in other programming languages; however, Python uses its own syntax. We will first explore
how to create for loops in Python.
The structure of a for loop is for item in sequence:. The loop is followed by indented lines of code
that are to repeat. The item defined in the loop will be used to reference the elements of the sequence.
We are going to create a for loop that prints out the items of a list. Type the following lines of code in
the Python interpreter to create a for basic loop:
items=[1, 2, three, four]
for i in items:
print i

Page 28

Software Training for Students (STS)

STS Manual Template

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:
for i in range(len(name)):

print name[i]


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



Software Training for Students (STS)

Page 29

STS Manual Template

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.

7.0 Standard Library

Python contains many built-in and importable modules through its standard library. These modules
contain functions that can be used while writing Python scripts and other modules. We have already
used parts of Pythons standard library: the math module.

7.1 The Math Module

The math module contains a number of useful functions that we have previously used. You were able to
import the math module by typing import math into the Python interpreter. Here is an example:

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

Software Training for Students (STS)

STS Manual Template

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.

7.2 The Random Module

Random numbers are used frequently in computer programming. Python generates random numbers
using the random module from its standard library. Nearly all functions in the random module depend
on the basic random() function. This function generates a random float uniformly in the semi-open
range [0.0, 1.0). Python uses an extensively tested random number generator that has a wide range of
uses in programming. It is a deterministic function so not all applications are suitable, but those are
outside the scope of this course. Lets dive into the random() function by typing the following code
into the Python interpreter:
import random

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().

Software Training for Students (STS)

Page 31

STS Manual Template

The random module has a number of other functions that are further detailed in Pythons online

7.3 The Tkinter Module

Tkinter is a GUI (Graphical User Interface) package which exists inside the Python Standard
Library. Up until now all of our programs interact with the user using a text interface, but most of the
applications you use on a daily basis have a GUI (Word, Firefox, even the Python IDE and interpreter).
Tkinter is a collection of widgets that can be combined in a variety of ways to achieve a specific GUI.
For our purposes well build a super simple GUI in five lines to demonstrate the power and ease of use
of buillding a GUI in Python.
Because this package is in the Python Standard Library, all we have to do is import the package into
our workspace. We will use the wildcard notation to import all member functions into our namespace
like we did earlier with the Math function. Well also include the webbrowser package to add some
functionality to our GUI.
from Tkinter import *
from webbrowser import *
The first step is to create the parent or top-level widget which will act as a container and reference
point for all other GUI widgets.
root = Tk()
Now we can create button widget. Note that the first argument passed to the widget is a reference to the
parent widget we created. The string passed as a text argument will appear on the face of the button.
simpleButton = Button(root, text=dont click me)
The next step is to call a special member function of the button to pack the button into the application
frame. Behind the scenes Tkinter includes a geometry manager which is being called which arranges
the specific widget. The pack() function allows you to pass layout options to the geometry manager.
Lets add one more button. Well create the button in the same way as last time, but lets pass an
argument to the pack function to place the second button below the first. This button will also have
some added functionality using the command argument, but first we have to define a function to bind
the button to.

Page 32

Software Training for Students (STS)

STS Manual Template

def openBrowser():


simpleButton2 = Button(root, text=click me, command=openBrowser)

simpleButton2.pack(side = BOTTOM)
Youve probably noticed that none of the GUI widgets we have created are actually visible yet. In
order to spawn the window we must initiate the application loop. All GUIs use a constantly running
application loop that waits for user input or updates from behind the scenes and immediately updates
the GUI accordingly.

8.0 Creating a Functional

This course has provided an overview of the Python programming language. We have learned about the
different data types such as variables, strings, and lists as well as basic functions and control structures.
We will create a functional script that will take a text input from a user and write that information to a
file. This section will outline the lines of code to be written in a new Python window of the interpreter.
First, open a new window of the Python interpreter and save the file as script.py in the current
working directory.
At the top of your script.py file, Type the following lines of code:
text_answer = None
filename =storage.txt
These lines of code will initialize a variable that will take text input from the user to be written to a file.
The filename variable is what the written file will be saved as.
def take_input():

return raw_input("Please enter the line you would like to write:

Software Training for Students (STS)

Page 33

STS Manual Template

def write_file(text_answer):

confirmation = raw_input('Write line: "' + text_answer + '" to
file: "' + filename + '" (y/n):')

confirmation = confirmation.lower()

if confirmation == 'y':

file = open(filename, 'w')



def dump_file():

file = open(filename, 'r')

print "Printing off file: " + file.read()


We have created three functions named take_input(), write_file(), and dump_file().

The take_input function uses a built-in Python function called raw_input(). The argument for that
function is a prompt that will be displayed to the user. The input from the user is converted to a string.
In our case, the raw input will be returned by the take_input()function and will be saved to a
variable later.
The write_file() function is going to use a Python file object to open a text file, write the text
input, and save the file. The function will use raw_input() to get a response from the user, convert
it to lowercase, and then create the text file. The open() function has two arguments. The first is the
filename which will be opened and the second is the read/write properties of the file to be opened. The
w in the argument allows Python to write to the text file that is opened. The opened texted document
is set as the file object named file to be manipulated within the function. The .write() method is
specific to the file object in Python. This method will write data to the text file. Finally, the .close()
method will close the text file.
The dump_file() is going to to open the storage.txt file, read the contents of the file, and print it in
the Python interpreter. Notice in this function that the .open() function is opening this file to be read
indicated by the r in the functions arguments. The second line of this function is going to print the
prompt along with the file contents from the .read() method. The .read() method will read the
entire contents of the file object. The last line of the dump_file() function will close the file object.
Now that the main functions for our script have been written, its time to create the application loop that
will run these functions. Type the following lines of code into your script.py file:
while 1:

Page 34

Software Training for Students (STS)

STS Manual Template


if text_answer == None:

print "Text Value: No value entered!"


print "Text Value:", text_answer


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:

answer = raw_input('Enter "1", "2", or "3": ')

answer = int(answer)


if answer == 4:

elif answer == 1:


text_answer = take_input()

elif answer == 2:

Software Training for Students (STS)

Page 35

STS Manual Template

if text_answer == None:
print "Please enter an input first"


elif answer == 3:



print answer, ": No such option"


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

Software Training for Students (STS)

STS Manual Template

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.

Software Training for Students (STS)

Page 37

STS Manual Template

Follow the prompt and choose 1:

Follow the prompt and choose 2, selecting y to write the file:

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

Software Training for Students (STS)

9.0 Power of Python

(working title)

STS Manual Template

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.

9.1 Useful Snippets

The first example is actually using the same webbrowser module as you saw earlier but here we are
executing the module directly from the command line.
python -m webbrowser -t "http://www.python.org"
The next example allows you to set up a web server on your computer in only one line. The command
will take the current directory and turn it into your root web directory. We can pass it an optional
argument to specify which port we would like to use.
python -m SimpleHTTPServer
python -m SimpleHTTPServer 8080
This one liner can time a piece of python code. It is very useful for deciding between two similar ways
of achieving a task in python. You can pass any valid python statement as an argument.
python -m timeit '"-".join(str(n) for n in range(100))'
This next snippet is extremely useful if you want to examine your environment at a certain point in
a script, but dont want to open up a full blown debugging interface. After importing code from the
standard library you can use this line anywhere in a script to spawn a python interpreter.
import code; code.interact(local = locals())

9.1 Fun snippets

The next snippet demonstrates some more advanced features of the language. The built-in map function
allows you to execute a function on an iterable sequence. In this example a lambda function is used
for the function and the code range(4) creates a sequence. The lambda keyword in Python allows
you to create an anonymous function (a function without a name, acts like a literal function). For more
information on map and lambda refer to the Python documentation.

Software Training for Students (STS)

Page 39

STS Manual Template

print map(lambda x: "Happy Birthday" + (" to you" if x != 2 else
"dear Name"),range(4))
Finally, here are a couple funny python snippets. Include these in a script or run them on the interpreter.
import this
import antigravity

Page 40

Software Training for Students (STS)

STS Manual Template

Software Training for Students (STS)

Page 41

STS Manual Template

Page 42

Software Training for Students (STS)

STS Manual Template

Software Training for Students (STS)

Page 43

STS Manual Template

Page 44

Software Training for Students (STS)

STS Manual Template

Software Training for Students (STS)

Page 45

STS Manual Template

Page 46

Software Training for Students (STS)

STS Manual Template

Software Training for Students (STS)

Page 47