Wednesday 23 July 2014

Subroutines: Procedures and Functions


It is possible to write a whole program as one big block but where possible we want to 
break it down into subroutines. There are several advantages to this: 

- The program becomes easier to read. 
- The program becomes easier to test. If you have tested a subroutine you don’t have to 
worry about it when you subsequently use it. 

- Subroutines can often be reused meaning code does not need to be rewritten. 
We will start off with a function that prints out This is my subroutine 3 times. Notice 
how the subroutines come before the main program. 

#Subroutine that prints out sentence 3 times 

def myFirstSubroutine(): 
 for i in range(1,3): 
 print('This is a subroutine') 
#Main Program 
print('Start of main program') 
myFirstSubroutine() 
print('End of program') 

This would output: 
Start of main program 
This is a subroutine 
This is a subroutine 
This is a subroutine 
End of program 


We can use parameters to make subroutines even more useful. The parameters in the 
subroutine below are text and times. 

#Subroutine that prints out sentence 3 times 
def myFirstSubroutine(text, times): 
 for i in range(0,times): 
 print(text) 

#Main Program 
print('Start of main program') 

myFirstSubroutine('Sample text',5) 
print('End of program') 

What is Selection


How to Screenshot in 1983.

Wednesday 16 July 2014

Data Representation

Data Representation 

Data Representation –  So far we’ve been talking about data as something that’s just swimming about being poked into logical sequences, and told to form orderly patterns and generally shape up. Without identifying the different characteristics of data it’s like looking at a sea of insects as a heaving mass of movement rather than identifying each insect by its species or its purpose.
.
Firstly, let’s separate data into two groups: analogue and digital
Analogue data is readable in real time and we read its information as a continuous process. We live our lives in analogue and we receive a continual stream of data via all our senses.
Digital data, in contrast, are made up of separate elements that in their most basic forms are the two numbers 0 and 1, the building blocks of binary language.
Now that we’re paddling in the gene pool of digital data, let’s looks at the single-celled amoeba of digital life as we know it: the bit. A bit is either 0 or 1. Next we have a nibble, which is four bits. You could say that 0 is a bit of a nibble. Or not. Anyway, on to the byte! A byte is eight bits, which also means it’s two nibbles. So a byte is two nibbles, a nibble is four bits, and a bit is a 0 or a 1.
Moving towards the deeper end of the digital gene pool, we find the bigger beasts like Kilobytes at 1024 bytes, Megabytes at 1024 Kilobytes, and the most powerful beast of them all, so far, which is the Yottabyte.
Here are three more digital data groups, and the first of these is the American Standard Code for Information Exchange, or ASCII, This uses binary code as a key to refer to 128 different characters and symbols, in the same kind of way that a spy might set up a code for passing secret information.
You’ll know about MP3 sound files of course. A music or sound file is a sequence of binary code that represents the patterns of sound waves, and the better the sound quality, the bigger the file, because a greater number of plotted points along the digital sound wave will take up more space.
Lastly, how about video? Again, for high quality video the file size is going to be ginormous and far too big for even a five minute video to be edited on a basic computer. How do you get round this? By compressing each frame of the film into a Moving Pictures Expert Group file, or MPEG,

TURTLE METHODS IN PYTHON

OVERVIEW AVAILABLE TURTLE AND SCREEN METHODS

Python Turtle Competition

What kind of picture can you make using Python and the Turtle Library?
What does this make? You will need to indent the loop?

from turtle import *
cat=100
loops = 0
while loops < 100:
loops +=1
forward (cat)
backward (50)
right (90)
pencolor("red")
forward (50)
right (90)
forward (50)
right (90)
forward (40)
pencolor("Blue")
left (1)
cat=cat+5
done()

Selection


Python Turtle

Turtle basics

The numbers on the left are line numbers and don't need to be typed in. The codes on the right are Python commands and they have to be copied exactly as written. Make sure you copy all the symbols, and that everything is in the correct case.
1
2
3
from turtle import *
forward(100)
done()

Useful turtle commands

The parts of the line that come after a # are called comments, and are ignored by Python. You don't need to type them in.
left(90)        #turn left by 90 degrees
right(120)      #turn right by 120 degrees
pencolor("red") #change pen colour to red - note 'colour' is spelt 'color'
pensize(5)      #change the pen thickness to 5
penup()         #lift the pen up so we can move without drawing
pendown()       #put the pen down again
speed(0)        #draw as fast as possible

Important data types

  • An int (short for integer) stores an integer number, eg. 5
  • A float (short for floating point) stores a non-integer eg. 5.111
  • A string stores some text eg. "hello"

Operators

Basic mathematical operators:
 a + b
 a - b
 a * b
 a / c

Conversions

Converting from one data type to another:
#converts a string to a float
float("1.54")

#converts a string to an int
int("3")

#converts a float or an int to a string
str(2.5)

Variables

We can store some data in a variable using the = operator:
a = 10
b = "my stuff"
Then we can recall them by using their names:
print(a+5)
print(b)
And also update them:
a = a + 5
b = "hands off " + b

User Input

We can ask the user for a string (and store it in a variable called answer):
answer = raw_input("what is your name?")

Conditionals

This is how we write a program that can respond differently depending on the conditions in which it runs:
time = 12
if time < 12:
    print("morning!")
elif time >= 12 and time < 18:
    print("afternoon!")
else:
    print("evening!")
We have these to choose from:
  • == exactly the same as. 2 equals signs for comparison, 1 for variable assignment.
  • >= more than or equal to
  • > more than
  • <= less than or equal to
  • < less than
  • != not equal to

Loops

To loop forever:
while True:
    print "hello!!"
To loop a certain number of times we can use whilewhile will only loop the code after the : while its condition is True:
#make a variable to keep count
loops = 0

#keep running the code while the loops variable is less than 10
while loops < 10:
    print(loops)

    #increase the loops variable by 1
    loops = loops + 1

Libraries

We can use libraries to get extra functionality in our programs. For example, to sleep for some time:
import time
time.sleep(5)
Or to get a random number between 1 and 10:
import random
random.randint(1,10)

Functions

If we are copying and pasting the same code over and over, we can use a function to save time and improve readability. In this example the function is called my_funcand it needs 2 arguments (arg1, and arg2).
  • When we call the function we need to provide the right number of arguments
  • We can only call a function after it's been defined with the def keyword
#define the function
def my_func(arg1,arg2):
    print(arg1 * arg2)

#call it
my_func(10,100)

Multi-core processors

Multi-core processors


Have you ever been in the middle of a tedious chore and thought it might be easier if there were two of you to share the work? Believe it or not, this kind of thinking has led to continued improvements in computer performance!
AMD Quad Core
A commercial Quad-Core AMD Opteron processor. Note the four identical processing units situated adjacently on a single chip. Image Credit: Advanced Micro Devices, Inc. (AMD).
A computer’s central processing unit (CPU) is very much like its brain. The CPU performs the fundamental steps required to run a computer program, such as basic mathematics and logic operations, through very tiny electronics components called transistors. Electronics specialists keep finding ways to build smaller, higher-frequency transistors, so that every new model of CPU can hold even more "brain" power!
In fact, since the mid-1960’s, the number of transistors that can fit on a chip has doubled approximately every two years, a trend referred to as "Moore’s law." Unfortunately, while in theory more, higher-frequency transistors mean faster calculations, too many can cause the CPU to generate a great deal of heat, which counteracts at least some of the improvements.
Instead of using more transistors to create more complicated CPUs that operate at high frequencies and produce a lot of heat, why not combine several simpler processing units to perform the task in less time? This is quite like getting some friends to help you with a chore instead of rushing to get it done alone. Computer designers first tried this by connecting multiple processors to each other. However, it can take a longer time for signals to travel between separated CPUs than it does to travel within a single, small unit, which can limit the improvements. It wasn’t until the mid-nineties when one research group put several processing units on the same tiny piece of silicon, and the multi-core processor was born. Over the next decade or so, the idea caught on! Today, multi-core processors are used to make computers, from smartphones to servers, more responsive and powerful with decreased heat generation.







Sorting Algorithms

Sorting Networks


Bubble Sort and Quick sort

When sorting lists of some specific size, sorting networks are often employed. These are very simple devices that only do compare-exchange operations. A compare-exchange operation on the pair <x, y> is merely the following code.
if x > y then {t = x; x = y; y = t}



what did we learn from this?


Does did the direction matter?





5 Element Sorting network





What does this network do?


How to sort in Python

For example, here’s a case-insensitive string comparison:
>>>
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.
A common pattern is to sort complex objects using some of the object’s indices as keys. For example:
>>>
>>> student_tuples = [
    ('john', 'A', 15),
    ('jane', 'B', 12),
    ('dave', 'B', 10),
]
>>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]





Tuesday 15 July 2014

Subroutines: Procedures and Functions





Documenting Code




Data Types


Scratch to Python Cheat Sheet


Scratch
Python
Hat blocks - starting point
in idle, press f5 to run the module
Stack blocks - do stuff
first type: from turtle import *
pensize(5)
color(“blue”)
penup()
pendown()
left(15)
forward(10)
Boolean blocks - is something true or not
x > 10
C blocks - looping and asking questions
if x > 10:
    do something
while True:
    do something
x = 0
while x < 10:
    x = x + 1
    do something
Variables - store a value
x = 10

What is Repetition?


Monday 14 July 2014

Input and Output



Input and output

For the system to work there is an input and an output. The process is taking the input and doing something with it - modifying it in some way - and producing an output.
In a computer system the processing will be done by a microprocessor of some kind.
Feedback is the output fed back to the input. The cruise control flowchart is an example of negative feedback because the speed is always kept at the same value. Positive feedback would push the speed away from the desired value.

Examples of inputs

  • keyboard
  • mouse
  • microphone
  • scanner
  • camera
  • pressure sensor
  • temperature sensor
  • magnetic sensor
  • moisture sensor
  • light sensor

Examples of outputs

  • printers
  • speakers
  • motors
  • monitors
  • heaters
  • electromagnets
  • bulbs/LEDs
For another example of feedback view the computer-controlled greenhouse in the computer control revision bite.

Year 10 Python Assessment Sheet

Python Y10 Assessment


In the lesson today, you must work independently through the following challenges. When each challenge is complete, tick and sign the sheet. Your teacher will verify this at a later time. Everyone should be able to complete the blue challenges, most should be able to complete the yellow challenges and some should be able to complete the orange challenges


Complete all of the challenges in the same file. Each challenge should be commented at the start of the code, for example #challenge1

You are allowed to use your previous work and/or the Internet to help you.

House Champions 2013-14



Monday 7 July 2014

Demonstrates type conversion in Python

# Trust Fund Buddy - Good
# Demonstrates type conversion

print(
"""
                       Trust Fund Buddy

Totals your monthly spending so that your trust fund doesn't run out
(and you're forced to get a real job).

Please enter the requested, monthly costs.  Since you're rich, ignore pennies
and use only dollar amounts.

"""
)

car = input("Lamborghini Tune-Ups: ")
car = int(car)

rent = int(input("Manhattan Apartment: "))
jet = int(input("Private Jet Rental: "))
gifts = int(input("Gifts: "))
food = int(input("Dining Out: "))
staff = int(input("Staff (butlers, chef, driver, assistant): "))
guru = int(input("Personal Guru and Coach: ") )
games = int(input("Computer Games: "))

total = car + rent + jet + gifts + food + staff + guru + games

print("\nGrand Total:", total)

input("\n\nPress the enter key to exit.")