# Intro to Python¶

In almost all cases, programming is about three things: 1) Saving data as variables. 2) Manipulating and comparing data (usually using fuctions). 3) Looping.

## Variables¶

In Python you can just use them (no declarations and no types) possible values: numbers (ints, floating point, complex) characters, strings, collections (arrays, lists, and dictionaries)

In [1]:
message = "Hi"
print message
age = 5
print age
print age;

Hi
5



Clearly sometimes you will want to manipuate your date. You can do simple things like add, subtract, multipy, divide, and concatenate very easily. The computer will let you add numbers, but not numbers and strings. age = 35 print age print age + 2 //IF the value stored in the variable "age" is a number, print the value plus 2 (String would concatenate) print age / 5 //IF the value stored in age is a number, divide it by 5 print age / 6 //IF the value stored in age is a number, divide it by 6 print age % 6 //IF the value stored in age is a number find the remainder when divided by 6

In []:
age = 35
print age
print age + 2
print age / 5
print age / 6
print age % 6

In []:
message = "Hi"
print message


## Strings¶

Strings are amongst the most popular types in Python. Python treats single quotes the same as double quotes (but be consistent). Double quotes do allow you to enclose single quotes. There are also triple double quotes """...""" They allow you to write strings that span multiple lines.

There are many, many built-in functionalities that you will eventually learn. It is impossible to cover (and remember) them all in one sitting.

#### Accessing parts of String¶

You can access an antire string variable, or just parts. To access just parts you use square brackets to specify the index of the data you want.

In []:
  message = "Hello Everyone"
print "The first letter]: ", message[0]
print "The 2nd through 9th letters: ", message[1:10]


#### String operators¶

String operators are special bits of code that ONLY WORK ON STRINGS. For instance, we have already seen that "+" does addition on numbers, but will concatenation on Strings.

+         Concatenation - Adds values on either side of the operator
*         Repetition - Creates new strings, concatenating multiple copies of the same string     a
[]         Slice - Gives the character from the given index    (A negative number starts from the end)
[ : ]     Range Slice - Gives the characters from the given range
in         Membership - Returns true if a character exists in the given string
not in     Membership - Returns true if a character does not exist in the given string

In []:
a = "Hello"
b = "Python"
print a + b
print a * 5
print "H" in a
print "z" in a
print "H" not in a
print "z" not in a

print b[-1]
print b[-2]
print b[-6]


#### String methods¶

String methods are similar to operators in that they manipulate data, but they are used very differently. Methods use the dot notation. This means that you put the name of the variable, a dot ("."), the name of the method, and then paratheses. Sometimes you need to put parameters in the parantheses. Parameters are extra pieces of information that are needed to figure out the desired answer.

For instance, one useful method is count, it returns the number of times a substring shows up in a variable. If you want the count method to return something, you better tell it what you are looking for. a = "Hello" print a.count('l') //This is an "el" not a number 1.

In []:
a = "Hello"
print a.count('l')
print a.count('o')
print a.count('z')


Some methods have optional parameters. These are pieces of information you can give, but aren't necessary. For instance, the count method can also take a start and end index.

In []:
a = "Hello there Sheila"
print a.count('l', 5)
print a.count('l', 5, 10)


Here are some additional String methods: find(), lfind(), rfind(), index(), isalnum(), isalpha(), isdigit(), len(), strip, lstrip(), rstrip(), split()

In []:
str = "Value 1, Value 2, Value 3, Value 4";
print str.split( );
print str.split(',');


## Lists¶

The value returned by split is a list. The list is a most versatile datatype available in Python. It is a sequence of comma-separated values encased by square brackets. Items in a list do not have to be of the same type.

In []:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
print me
print you

In []:
for info in me:
print info


In []:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
people = [you, me]
print people

In []:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
people = [me, you]
print people


#### Built-in List Functions and Methods¶

Lists have a number of functions and methods associated with them.
Some functions include: cmp(list1, list2) len(list) max(list) min(list) list(seq)

Some of the methods are: count(), index(obj)

Some list methods are in-place. This means that the lists are changed, but the methods don't "return" anything. These include sort(), reverse(), insert(), append(), and remove.

In []:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]
print people

print "\nList Functions \n"
print cmp(me, you)
print len(people)
print max(people)
print min(people)

print "\nList Methods\n"
print people.count('Colleen')
print people.count(me)

people.sort()
print people

people.reverse()
print people

people.append(['Becca', 'van Lent', 5, 'F'])
print people

people.insert(2, ['Chris', 'van Lent', 7, 'M'])
print people


## Now what?¶

Lets do a little input using the raw_input() function.

In [14]:
message = raw_input("Enter your input: ")

print message
print message.find("Colleen")
print message.count("l")
print message.index(" ")
print message.rfind(" ")

Enter your input: Colleen is here is here is here
Colleen is here is here is here
0
2
7
26



## Flow of Control¶

The real power of computing is selection and repetition. Selection is when you use comparison operators to direct which path the program should take. Repetition is when code is executed multiple times.

In [3]:
num_cookies = 5
print "Yum!!"
print "Only " + str(num_cookies) + " left"
print "I am full now."

Yum!!
Only 4 left
Yum!!
Only 3 left
Yum!!
Only 2 left
Yum!!
Only 1 left
Yum!!
Only 0 left
I am full now.



The indentation is VERY, VERY important. You must be consistent, do don't use tabs. The other thing you need to be VERY worried about is the possibility of infinite loops. Go back up and change the code to num_cookies = 0 or add one instead of subtracting one.

In [6]:
age = 25
if age < 18:
print "Minor"
elif age > 100:
print "Centenarian"
elif age > 65:
print "Senior"
else:


Enter your age: 56


In [8]:
num = 0
while num <=10:
if num % 2 == 0:
print num
num +=1

0
2
4
6
8
10



## Loops and list¶

In [11]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]
for  i in range(len(people)):
print i, people[i]

0 ['Colleen', 'van Lent', 40, 'F']
1 ['Bob', 'McCarthy', 50, 'M']
2 ['Sally', 'James', 25, 'Unknown']
3 ['John', 'Doe', 18, 'M']



There is a shortcut you can use when you wan to loop through lists..

In [10]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
her = ["Sally", "James", 25, 'Unknown']
him = ["John", "Doe", 18, 'M']
people = [me, you, her, him]

for person in people:
print person

['Colleen', 'van Lent', 40, 'F']
['Bob', 'McCarthy', 50, 'M']
['Sally', 'James', 25, 'Unknown']
['John', 'Doe', 18, 'M']



Functions

We have already used functions in this tutorial. A function is a block of reusable code that is used to perform a single (albeit possibly complex). Functions allow for code reuse and also allow you to work better as a team. The process of defining a function is as follows:

1) Function blocks begin with the keyword def followed by the function name, parentheses ( ), and colon

def myFunction():

2) Any input parameters or arguments should be placed within these parentheses.

def printMeALot(msg, times):

3) The code block within every function is indented.

def printMeALot(msg, times): for i in range(times): print msg

4) Any return statements will cause an exit from the a function

5) A return statement can pass an expression back to the caller. A return statement with no arguments is the same as return None.

In [13]:
def printMeALot(msg, times):
for i in range(times):
print msg

printMeALot("I am the greatest", 10)

I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest
I am the greatest



In the example above we wrote a function, called a built-in function (range), and called our own function. We also called the print function. In the latest versions of Python, print has been changed to a function again.

# Turtle Programming¶

If you haven't already, it is time to crash your code. I am going to introduce something new that doesn't work particularly well in iPython Notebook. The key to know is that the square icon above will stop the program from running. (Also useful to know in the case of infinite loops.)

The Turtle program is simple to use and is meant to help beginner programs with a visual representation of a "turtle" moving around the screen. Once you run this program, you need to use an IDE or just a text editor to write you own program. I would like you to write three functions, each of which will dispaly one initial in your name. Then, call all three functions in succession.

To use the Turtle program you will need to import it from the libraries.

In [14]:
import turtle
import random

turtle.penup()
turtle.goto(-25, 200)

turtle.fillcolor("yellow")
turtle.begin_fill()
turtle.circle(50)
turtle.end_fill()

for x in range(10):
# choose a random spot
xpos = random.randint(-200,200)
ypos = random.randint(-200,200)

# goto this spot
turtle.penup()
turtle.goto(xpos, ypos)
turtle.pendown()

# generate a random color
red = random.random() # returns a number between 0 and 1
green = random.random()
blue = random.random()

turtle.pencolor(red,green, blue)

turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)

raw_input("press enter to exit ")

press enter to exit


Out[14]:
''

In []: