Python Night

A Presentation By The Computer Science Department

print "Hello World"

Installing Python

Mac

Windows

Go here: https://www.python.org/downloads/release/python-350a1/

Click One of These:

Let us know when done installing

Loading

Ready 

Run...

Pycharm would be the next get.

Language
Compiler

IDE

What's the difference?

What are they for?

What is what for our purposes?

Getting Started

__author__ = "Foo Getch"

print ("Hello World")

Numbers

4 + 5 # This will return 9

4.3 + 5.1 # This will return 9.4

I heard you like Math?

6 * 5

4/3 # Whole numbers only

4.0/3 # Decimals too

6 % 2 

Not the Show

  • First programmers were math people
  • Python removes some of that.
  • % returns the remainder

Words

'a'+'b'           # 'ab'

s = 'Python'      # s[0] = 'P'
s[:2] + [2:]      # = 'Python'


s[-1]             # 'n' 

len(s)            # 6

With Friends

Strings are immutable

No out of bounds errors

Much nicer than in other languages

Some Little Practice

'Strings?'

'a'+'b'

'apples' == 'oranges'

'apples' < 'oranges'
# If you haven't guessed
# These are Comments
# Compiler Skips these
# Want people to understand your code
# Use Comments

(1,4) # tuple

(1,4,9) # triple

4 += 2 # 6

8 *= 2 # 16

x = 'apple'  y = 'oranges'

x < y #true

True > False # True

Comparisons are True/False

Assignments

A single = sign

Comparisons

It's useful to be able to compare things.

x = 3

y = 6

6 = z # This won't work

All LValues are RValues

 

RValues are not LValues

# All comparisons return a 
# Boolean Value

4 <= 1 
5 >= 1

x = True
y = False

x > y 

x == Y 

x != y 

x is x 

[] is [] 

If
Elif
Else

If blah then do this

Else if blah then do this

If all else fails do this

Blah is one of those True/False things

Conditionals and You



print 'I am an automated division program, I only know how to divide'
print 'Do not divide by zero though because it makes me break'

num = input('Divide this number')
den = input('By this number, just dont let it be zero pls')

if den == 0:
    print 'WHY DID YOU DO THIS TO ME YOU MONSTER'

elif den == 1:
    print 'Ha easy ', num, 'divided by', den, 'equals ', num/den

elif den == 2:
    print 'Dont you have anything harder, the answer is ', num/den

elif den < 0:
    print 'You can't fool me! The answer is ', num/den 

else:
    print 'I wonder if I will ever learn to love ', num/den

While
For

Range

While blah do this

For blah times do this

We'll need these

Meanwhile 

i = 1
while i < 10:
    print i
    i+=1

x = 'a'

while i > 0:
    i-=1
    print "I speak for the trees \n"

    while i != 'aeeee':
        x += 'e'
        print x
        

Nested loops are a thing.

Wherefore and range too I guess

for i in range(10):
    print i # 1,2,3,4,5,6,7,8,9,10

for i in range(10,15):
    print i # 10,11,12,13,14,15

for i in range(0,10,2)
    print i # 0,2,4,6,8,10

for i in "Hello World"
    print i

Be aware of break and continue

for i in range (10,0,-1):
    if i==0: break
    print 10/i

j = 0
message = "Hello Sunshine"

while(j<=5):
    if j == 1: continue
    print message[j]
    j+=1

Sometimes you want things to end early

Functions

Why bother with functions?

Empowering your programming

Boosting readability 

Everyone Remembers Their First

def helloWorld(name):
    return "Hello " + name

def times2(num):
    return num *2

But, everyone uses other people's stuff.

import numpy
import numbers
import scipy
import requests
import Pillow
import SQLAlchemy
import Pygame
import IPython

Practice Thyme:

  • Speed Radar.
  • Finn the Enthusiastic Kid!
  • Leap Year?

Speed Radar

You're to put together a program which determines if cars are going the speed limit.

 

If more than 10 percent of the cars are breaking the speed limit the function should return 0

 

Otherwise return the average speed of all the cars that are not breaking the speed limit.

radar(minSpeed, maxSpeed, values){


}

Finn the Human!

Finn can be a bit rude.

If you don't say anything to him he says "Fine be that way"

If you say something loudly, he says "Woah chill out"

He only says "Sure" when asked a question.

Otherwise he says whatever

 

finnSays(input){


}

Leap Year?

Write a program which determines if this year is a leap year or not.

A leap year occurs on every year divisible by 4

Except if that year is also divisible by 100

Unless it's also divisible by 400

leapYear(year){

}

Leap Year in Haskell

leapYear :: (Integral a) => a -> String
leapYear a 
  | mod a 4 == 0 && mod a 100 /= 0 = "Leap Year!"
  | mod a 400 == 0 && mod a 100 == 0 = "Leap Year!"
  | otherwise = "Not a Leap"

Data Structures

Different Sized Boxes

A variable holds one value

 

 

An array holds many values

x = "The King of France is named Roliere"
arrayOfInt = [1,2,3]
arrayOfFloat = [1.0, 2.5, 3.14] 

arrayOfArrayOfArray = [[1,2,3],[3,2,1],[2,1,3]]

These are one of the most useful tools in our box

Array Exercises Here

Reverse the contents of an array

"""
Write a function reverse which takes an array and reverses its contents
For added challenge do this without creating a new array
"""


x = [1,2,3]
reverse(x)     # [3,2,1] 

Conway's Game

#----------------------------------------------
__author__ = usingPython
#----------------------------------------------

import random
import time
import os

#---------------------------------------------------------------------------

def initGrid(cols, rows, array):
    for i in range(rows):
        arrayRow = []
        for j in range(cols):
            if (i == 0 or j == 0 or (i == rows - 1) or (j == cols - 1)):
                arrayRow += [-1]
            else:
                ran = random.randint(0,3)
                if ran == 0:
                    arrayRow += [1]
                else:
                    arrayRow += [0]
        array += [arrayRow]

#---------------------------------------------------------------------------
    
def printGen(cols, rows, array, genNo):
    os.system("cls")

    print("Game of Life -- Generation " + str(genNo + 1))
    
    for i in range(rows):
        for j in range(cols):
            if array[i][j] == -1:
                print("#", end=" ")
            elif array[i][j] == 1:
                print(".", end=" ")
            else:
                print(" ", end=" ")
        print("\n")

#---------------------------------------------------------------------------

def processNextGen(cols, rows, cur, nxt):
    for i in range(1,rows-1):
        for j in range(1,cols-1):
            nxt[i][j] = processNeighbours(i, j, cur)

#---------------------------------------------------------------------------
      
def processNeighbours(x, y, array):
    nCount = 0
    for j in range(y-1,y+2):
        for i in range(x-1,x+2):
            if not(i == x and j == y):
                if array[i][j] != -1:
                    nCount += array[i][j]
    if array[x][y] == 1 and nCount < 2:
        return 0
    if array[x][y] == 1 and nCount > 3:
        return 0
    if array[x][y] == 0 and nCount == 3:
        return 1
    else:
        return array[x][y]

#---------------------------------------------------------------------------
############################################################################
#---------------------------------------------------------------------------

ROWS = 10
COLS = 10
GENERATIONS = 10
DELAY = 0.4

thisGen = []
nextGen = []

initGrid(COLS, ROWS, thisGen)
initGrid(COLS, ROWS, nextGen)

for gens in range(GENERATIONS):
    printGen(COLS, ROWS, thisGen, gens)
    processNextGen(COLS, ROWS, thisGen, nextGen)
    time.sleep(DELAY)
    thisGen, nextGen = nextGen, thisGen
input("Finished. Press <return> to quit.")

Python Night

By Matthew FancyPants Getch