Python, iPython, and the basics
Presented By: Joshua R. Smith
Based on Lecture Materials By: Milad Fatenejad with contributions from Katy Huff, Tommy Guy and Many More
In this lecture, i'm going to talk about programming; specifically the python programming language. In order to do the examples, we are going to have to use an environment called iPython which I'll also talk about. I expect this lecture to be interactive, so stop me at any point if you have questions. Finally, I want everyone to understand that fundamentally computing is about people. The correct power dynamic is that people are the mastes and the machines are servants. The machines are there to make our lives easier. Programming is an act of written communication between people across time and space. Computers are just the medium.
So now would be a good time to roll out PEP 20, The Zen of Python
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
This lecture will be structured as follows: I will be teaching the basics of two things: the python programming language (to a greater extent) and the ipython interpreter (to a lesser extent). The ipython interpreter is one of many different ways to implement python code. As far as the python component, I'll shoot for a layered approach: I'l continue building on my previous concepts. It turns out that like any sufficiently complex topic, its not really possible to force the pedagogy into a serial stream. Also, we have a pretty serious time constraint. I'm just going to drop it on you. Because of the brief nature of this tutorial, I've included links to some excellent reference material. Also, if we have time, I'll take questions based on the specific programming needs of this class.
Here is the reference material.
- Dive into Python
- Software Carpentry's Python Lectures
- IPython: A System for Interactive Scientific Computing
- How to Think Like a Computer Scientist
Once we briefly deal with ipython, I'll cover python in the following order:
What I'll cover
- print statements
- type coersion
- basic operations: add numbers, concatenate strings, basic data type functionality
- file reading
- for loop
- conditional (if) statements
- while loops
- writing to files
ipython is the tool that we are going to use to execute python commands and code. iPython is an alternative to the built-in Python interpreter with some nice features. Lets give the built-in interpreter a spin just this once.
jrsmith3@zoidberg:~$ python Python 2.7.2+ (default, Oct 4 2011, 20:03:08) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "hello world" hello world >>> quit()
We can also write python commands in a file and execute them from the command line. You will notice that the print command above is located in the file hello.py. Execute the following command at the command line
jrsmith3@zoidberg:~$ python hello.py
iPython has more useful features than the standard python interpreter, so we'll use it from here on out.
jrsmith3@zoidberg:~$ ipython In : print "hello world" hello world In :
You can paste things into the ipython console by copying text from your machine with ctrl+c and typing %paste at the iPython prompt.
iPython has a history. If you press the up and down keys, you can access the history.
iPython also has tab completion of previous commands. Try typing "print" and then hit the tab key.
iPython has some nice help features. Lets say we want to know more about the integer data type. There are at least two ways to do this task:
In  help(int)
In  int?
If you wanted to see all the commands available for something, use the dir command. Check out all of the methods of the str type.
In  dir(str)
Executing code in files
If your code is in a file, you can execute it from the iPython shell with the %run command. Execute hello.py like so
In  %run hello.py
To clear everything from iPython, use the reset command.
In  reset Once deleted, variables cannot be recovered. Proceed (y/[n])?
All programming languages have variables, and python is no different. To create a variable, just name it and set it with the equals sign. One important caveat: variable names can only contain letters, numbers, and the underscore character. Lets set a variable.
In : experiment = "current vs. voltage" In : print experiment current vs. voltage In : voltage = 2 In : current = 0.5 In : print voltage, current 2 0.5
Types and Dynamic Typing
Like most programming languages, things in python are typed. The type refers to the type of data. We've already defined three different types of data in experiment, voltage, and current. The types are string, integer, and float. You can inspect the type of a variable by using the type command.
In : type(experiment) Out: <type 'str'> In : type(voltage) Out: <type 'int'> In : type(current) Out: <type 'float'>
Python is a dynamically typed language (unlike, say, C++). If you know what that means, you may be feeling some fear and loathing right now. If you don't know what dynamic typing means, the next stuff may seem esoteric and pedantic. Its actually important, but its importance may not be clear to you until long after this class is over.
Dynamic typing means that you don't have to declare the type of a variable when you define it; python just figures it out based on how you are setting the variable. Lets say you set a variable. Sometime later you can just change the type of data assigned to a variable and python is perfectly happy about that. Since it won't be obvious until (possibly much) later why that's important, I'll let you marinate on that idea for a second.
Here's an example of dynamic typing. What's the type of data assigned to voltage?
In : type(voltage) Out: <type 'int'>
Lets assign a value of 2.7 (which is clearly a float) to voltage. What happens to the type?
In : voltage = 2.7 In : type(voltage) Out: <type 'float'>
You can even now assign a string to the variable voltage and python would be happy to comply.
In : voltage = "2.7 volts" In : type(voltage) Out: <type 'str'>
I'll let you ruminate on the pros and cons of this construction while I change the value of voltage back to an int:
In : voltage = 2
It is possible to coerce (a fancy and slightly menacing way to say "convert") certain types of data to other types. For example, its pretty straightforward to coerce numerical data to strings.
In : voltageString = str(voltage) In : currentString = str(current) In : voltageString Out: '2' In : type(voltageString) Out: <type 'str'>
As you might imagine, you can go the other way in certain cases. Lets say you had numerical data in a string.
In : resistanceString = "4.0" In : resistance = float(resistanceString) In : resistance Out: 4.0 In : type(resistance) Out: <type 'float'>
What would happen if you tried to coerce resistanceString to an int? What about coercing resistance to an int? Consider the following:
In  resistanceString = "4.0 ohms"
Do you think you can coerce that string to a numerical type?
On Being Precise with floats and ints
Again, the following may seem esoteric and pedantic, but it is very important. So bear with me.
Lets say you had some voltage data that looks like the following
0 0.5 1 1.5 2
Obviously, if you just assigned this data individually to a variable, you'd end up with the following types
0 -> int 0.5 -> float 1 -> int 1.5 -> float 2 -> int
But what if you wanted all of that data to be floats on its way in? You could assign the variable and then coerce it to type float:
In : voltage = float(1)
But that's ugly. If you want whats otherwise an integer to be a float, just add a period at the end
In : voltage = 1. In : type(voltage) Out: <type 'float'>
This point becomes important when we start operating on data in the next section.
In this section all of the discussion in the previous section becomes important. I don't know if I'd call this stuff fundamental to the language, but its pretty important and it will zing you if you aren't careful. The takeaway is that you need to be precise with what you are doing. Lets say you want to add some integers.
In : a = 1 In : b = 2 In : c = a+b In : c Out: 3 In : type(a), type(b), type(c) Out: (<type 'int'>, <type 'int'>, <type 'int'>)
So we got a vale of three for the sum, which also happens to be an integer. Any operation between two integers is another integer. Makes sense.
So what about the case where a is an integer and b is a float?
In : a = 1 In : b = 2. In : c = a + b In : c Out: 3.0 In : type(a), type(b), type(c) Out: (<type 'int'>, <type 'float'>, <type 'float'>)
You can do multiplication on numbers as well.
In : a = 2 In : b = 3 In : c = a * b In : c Out: 6 In : type(a), type(b), type(c) Out: (<type 'int'>, <type 'int'>, <type 'int'>)
In : a = 1 In : b = 2 In : c = a / b In : c Out: 0
Here's why type is important. Divding two integers returnes an integer: this operation calculates the quotient and floors the result to get the answer.
If everything was a float, the division is what you would expect.
In : a = 1. In : b = 2. In : c = a / b In : c Out: 0.5 In : type(a), type(b), type(c) Out: (<type 'float'>, <type 'float'>, <type 'float'>)
There are operations that can be done with strings.
In : firstName = "Joshua" In : lastName = "Smith" In : fullName = firstName + lastName In : print fullName JoshuaSmith
When concatenating strings, you have to be explicit since computers don't understand context.
In : fullName = firstName + " " + lastName In : print fullName Joshua Smith
There are other operations deined on string data. Use the dir comnand to find them. One example I'll show is the upper method. Lets take a look at the documentation.
In : str.upper? Type: method_descriptor Base Class: <type 'method_descriptor'> String Form: <method 'upper' of 'str' objects> Namespace: Python builtin Docstring: S.upper() -> string Return a copy of the string S converted to uppercase.
So we can use it to upper-caseify a string.
In : fullName.upper() Out: 'JOSHUA SMITH'
You have to use the parenthesis at the end because upper is a method of the string class.
For what its worth, you don't need to have a variable to use the upper() method, you could use it on the string itself.
In : "Joshua Smith".upper() Out: 'JOSHUA SMITH'
That wraps up this lesson. We tried out the iPython shell and got some experience with ints, floats, and strings. Along the way we talked about some philosophy and how programming is about people.