Intro to Python 3

(Wait!?? What happened to Python2? Or Python1? I am a beginner? Shouldn't I start at the beginning?)

There are very few things you need to know as languages change from one version to another. The biggest problem is knowing which language your packages are expecting. In the past few years more and more applications have moved to Python3 which is why we are switching too. Unfortunately, even though the changes may not seem very big it is important to run the proper version else your program may crash. Spectacularly.

Getting Started

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

In [4]:
message = "Colleen"
print (message)
age = 5
print (age)
Colleen
5

Just assigning values and then printing them is boring. Same with big data, sometimes you will want to manipuate your data. You can do simple operations like add, subtract, multipy, divide, and concatenate very easily.
age = 35 print (age) print (age + 2) //IF the value stored in the variable "age" is a number, print the value + 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

The computer will let you add numbers, but not numbers and strings.

In [3]:
age = int("35")
print (age)
print (age + 2) 
print (age)
print (age / 5)
print (age / 4)
print (age % 4)
print (age)

#name = "Colleen"
#print (name+2)
35
37
35
7.0
8.75
3
35
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-19c64392b95e> in <module>()
      9 
     10 name = "Colleen"
---> 11 print (name+2)

TypeError: must be str, not int

Strings

Strings are an extremely popular data type in Python. This may be because computers often "read" numbers as strings. Python treats single quotes the same as double quotes, the main difference is that double quotes do allow you to enclose single quotes. You can use either convention, but the key is CONSISTENCY.

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 [6]:
  message = "Hello Everyone"
  print (message);
  print ("The first letter in message is: " , message[0])
  print ("The 2nd through 9th letters are: ", message[1:35])
Hello Everyone
The first letter in message is:  H
The 2nd through 9th letters are:  ello Everyone

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 perform 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 [7]:
a = "Hello"
b = "Python"
print (a + b)
print (a * 5)
print ("h" in a)
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 [-3])
HelloPython
HelloHelloHelloHelloHello
False
True
False
False
True
n
o
h

String methods

The string operators return information about a string and they are a part of the Python language. There is another set of tools called methods. 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 parantheses. For instance, since you don't always know if the person typed in a number or not, you can use the method isdigit() to find out.

variable.isdigit()

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 gorgeous" print (a.count('l'))
print (a.count('o')) print (a.count('O'))

In [8]:
a = "Hello there awesome super super awesome programmers"
print (a.count('l'))           #This is a lowercase letter l, not the number 1.
print (a.count('o'))
print (a.count('O'))           #This is an uppercase O, not the number 0
print (a.count('super'))
2
4
0
2

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 [11]:
a = "Hello there Sheila"
print (a.count('l', 5))
print (a.count('l', 5, 10))
1
0

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

In [14]:
print (a.find('t'))
print (a.find('z'))
print (a.index('t'))
#print (a.index('z'))   #What happens if I run this command?
6
-1
6

Just because a method exists doesn't mean you can always use it. In the example above we are asking Python to do find the index of a character that doesn't exist. Sometimes you need to combine commands, e.g. first make sure it exists, and then find it. This idea of "If/then" is something we will get to a little later.

Split and Lists

In [ ]:
str1 = "Value 1, Value 2, Value 3, Value 4";
print (str1.split( ));
print (str1.split(','));            #I picked the comma for a reason, can anyone guess why?

The value returned by split is a LIST. The list is THE 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 [15]:
me = ["Colleen", "van Lent", 40, 'F']
you = ["Bob", "McCarthy", 50, 'M']
print (me[0])
print (me[1])
print (me[2])
print (me[3])

#print (you)
#print (me + you)
Colleen
van Lent
40
F
['Bob', 'McCarthy', 50, 'M']
['Colleen', 'van Lent', 40, 'F', 'Bob', 'McCarthy', 50, 'M']

First taste of iternation (looping)

In [21]:
for info in me:
    print (info)
    
#for info in me:
#    print(info,"\t", end="")      #You can replace that \t with an empty space
    
Colleen
van Lent
40
F

Lists of lists

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

Built-in List Functions and Methods

Lists have a number of functions and methods associated with them Some of the functions are:

  • len(list) #Return the length of a list
  • max(list) #Return the "largest" element
  • min(list) #Return the "smallest" element
  • list(seq) #Take the seq, and turn it into a list

Some of the list methods are:

  • count()
  • index(obj) #Reminder -- some methods and functions have parameters - they are in the parantheses.

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 [24]:
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 (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)
[['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M']]

List Functions 

4
['Sally', 'James', 25, 'Unknown']
['Bob', 'McCarthy', 50, 'M']

List Methods

0
1
[['Bob', 'McCarthy', 50, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['John', 'Doe', 18, 'M'], ['Sally', 'James', 25, 'Unknown']]
[['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M']]
[['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Becca', 'van Lent', 5, 'F']]
[['Sally', 'James', 25, 'Unknown'], ['John', 'Doe', 18, 'M'], ['Chris', 'van Lent', 7, 'M'], ['Colleen', 'van Lent', 40, 'F'], ['Bob', 'McCarthy', 50, 'M'], ['Becca', 'van Lent', 5, 'F']]

Now what?

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

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

print (message)
print (message.find("Colleen"))
print (message.count("e"))
print (message.index(" "))
print (message.rfind(" "))
Enter your input: My name is Colleen.
My name is Colleen.
11
3
2
10

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.

Iteration

Iteration (also called repetition by some) is when code is executed multiple times even though you only wrote it down once. You signal to the computer that you may want to loop with a keyword such as for or while. You must include a test case with this word so the computer can figure out when to execute the code. The code you want to repeat must be indented.

In [34]:
num_cookies = 5
while num_cookies > 0:                               ## Very important colon at the end of this line.
  print ("Yum!  I love eating cookies!")             ## Notice that this line is indented
  num_cookies -=1                                    ## Notice that this line is indented
  print ("Only " + str(num_cookies) + " left..")     ## Notice that this line is indented 
print ("I feel a little full now.")                   ## Not indented here...
Yum!  I love eating cookies!
Only 4 left..
Yum!  I love eating cookies!
Only 3 left..
Yum!  I love eating cookies!
Only 2 left..
Yum!  I love eating cookies!
Only 1 left..
Yum!  I love eating cookies!
Only 0 left..
I feel a little full now.

The indentation is VERY, VERY important. You must be consistent, I recommend that you don't use tabs, use spaces!!. 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 [35]:
##Can you write a program that prints the numbers from 0 to 10 by 2?
print(0)
print(2)
print(4)
print(6)
print(8)
print(10)
0
2
4
6
8
10

Can you fix the code below to get the correct output?

In [38]:
num = 0
while num < 10:
    print(num)
    num+=2
    
0
2
4
6
8

If were to combine the looping construct for with the range function we get close, but not quite...

In [39]:
for num in range(10):
    print(num)
0
1
2
3
4
5
6
7
8
9

Selection

One problem with the example below is that we are executing all of the statements, even if we sometimes would rather skip them. What we want to do is use an if statement to only execute some students under certain situations. Here is a simple example.

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

Fixit Time

Can you use selection to fix our earlier code? Here is a tip, don't forget about the modulus operator %. It will find the reminder.

In [42]:
for num in range(10):
    print(num)
0
1
2
3
4
5
6
7
8
9

Loops and list

Because lists can contain a lot of data, it makes sense that we may want to use selection and iteration when using them.

In [43]:
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 [44]:
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 [46]:
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. To use the Turtle program you will need to import it from the libraries. The first program is a sample from python.org. The second program is a simple block. The third adds some random functions and colors.

When this eventually crashes your machine, use the restart icon above. It is the "refresh" arrow.

Can you make a block M?

In [ ]:
##FROM https://docs.python.org/3.2/library/turtle.html
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
    forward(200)
    left(170)
    if abs(pos()) < 1:
        break
end_fill()
done()
In [ ]:
from turtle import *

color('blue')
pencolor('yellow')
pensize(20)
pendown()
begin_fill()
forward(250)
right(90)
forward(250)
right(90)
forward(250)
right(90)
forward(250)
end_fill()
done()
In [3]:
from turtle import *
import random

pencolor(.5, 0, .2)  #RGB
goto(-300, 300)
pendown()
begin_fill()
for x in range(10):
    # choose a random spot
    xpos = random.randint(-500,500)
    ypos = random.randint(-500,500)
    goto(xpos, ypos)

    
#     generate a random color
    r = random.random() # returns a number between 0 and 1
    g = random.random()
    b = random.random()
    pencolor(r, g, b)
    
color(r,g, b)   
end_fill()
done()
In [ ]:
 
In [ ]: