Week 1, Wednesday: python basics

python vs unix shell

Opening a terminal window results in a unix shell, with the dollar-sign prompt. At that prompt you can type unix commands, like cd and ls.

Typing python at the unix prompt starts the python interactive shell, the the ">>>" prompt. At the python prompt you can type python code, like this:

>>> 5 + 10
15
>>> 5 * 10
50
>>> 5 - 10
-5
>>> 5 / 10
0

The above python session shows some integer math operations.

To get out of the python interactive shell, type Cntrl-d (hold the control key down and hit the "d" key).

types

Data types are important. To the computer, 5, 5.0, and "5" are all different. Three data types we will work with are: integers (int), floats (any number with a decimal point), and strings (str). A data type is defined by the possible data values, as well as the operation you can apply to them.

For example, a string is any set of zero or more characters between quotes:

And only the + and * operators are defined for strings:

>>> "hello" * 4
'hellohellohellohello'
>>> "hello" + "class"
'helloclass'

operators

All of the normal math operations are possible, as well as a few others: +,-,*,/,%,**

>>> 5 / 10.0    # floating-point math
0.5

>>> 15/6        # integer division
2
>>> 15%6        # remainder
3

>>> 2**4
16
>>> 2**5
32

variables, assignment

We use variables in our programs instead of raw data values. Once we assign data to a variable, we can use the variable name throughout the rest of our program.

>>> name = "Jeff"
>>> age = 50
>>> print(name + " is " + str(age) + " yrs old")
Jeff is 50 yrs old

simple functions

Python has many built-in functions. A function is just a grouping of code with a name assigned to is. We can execute the code in the function by calling the function. Here are some simple functions we will use:

Functions like raw_input() return something to the caller. We usually want to save what the called function returns to a variable. Here is an example:

>>> name = raw_input("What is your name? ")
What is your name? Jeff
>>> print(name)
Jeff
>>> year = raw_input("What year were you born? ")
What year were you born? 1965
>>> print(year)
1965
>>> type(year)
<type 'str'>
>>> year = int(year)
>>> type(year)
<type 'int'>

first program

Can you write a program that asks the user for the year they were born, and then calculates and displays their age?

 $ python howold.py
 Year you were born? 1965
 Sometime this year you will be 50 yrs old...

For now we will just do this in the interactive python shell. On Friday, once we know how to use the text editor, we will put our python code in a file and then run the file (like above).