CP104 Lecture Notes
CP104 Lecture Notes
Hardware Second algorithm (only works if list is sorted): cut the list in half and compare the number
- Cpu (central processing unit) you want to the middle if the middle is >, repeat in the left half of the list if the middle is
○ Brain <, repeat in the right half of the list.
- Memory (random access memory) Repeat - if matches the middle, STOP.
- Secondary Storage (discs, USB stick) Binary Search
- Input devices (keyboard, mouse, microphone)
- Output devices (printer, screen, speakers)
Software
- Operating system
○ Controls computer
- Utility Programs (AV, tasks, low level)
- Software development tools (assembler, compiler, interpreter)
- Applications (programs you write)
128 64 32 16 8 4 2 1
1 1 1 1 11 1 1 = 255
Lectures Page 1
Writing Programs
September-18-09
11:46 AM
2 Dimensional Maze
1) Solve maze
a. How to decide which way to go?
b. Will this give me all the ways?
2) Read in maze
3) Print maze
4) Represent maze
An enrolment problem
Your club is having a special event with a special speaker. The room only holds 100 people. You also
need to keep track of who has registered.
Print
- Print is a function in Python 3.0
Lectures Page 2
Comments
September-21-09
11:36 AM
Comments - sometimes the programmer wants to whisper something to the (human) reader. The
interpreter ignores them.
Variables
- A name that represents a value stored in the computer's memory
- We use variables to handle data. Once data is entered or created we need to be able to find it in
memory.
- We use assignment statements to assign a value to a variable.
Syntax
Output :
Lectures Page 3
Output :
The month is
September
Lectures Page 4
Reading Ahead PP 50-59
Variable (not integer division)
September-23-09
11:30 AM
Month = 'September'
Day = 21
Year = 2009
Print ('The date is {0}{1}, {2}.' .format (month,day,year))
//
September 21, 2009
Multiline comment:
'''
sdds
sdds
'''
Don't:
- Give your variables silly names. It makes the program hard to read.
- Use python keywords (P18) - if, print, while
- Use a space (variable names: no spaces)
- Use anything other than a,b,...,z; A,B,...Z, 0,1,2,...9, or _ in the body of the variable name.
- Start the variable name with a number, or anything other than a,b,...,z,A,B,...,Z, or _.
- Forget Python is case sensitive. Dyna =/= dyna
Just reassign it
Day =21
Print ('the day is {0},' . format(day))
Day = 23
Print ('the day is {0},' .format(day))
- Python decides type based on context. Many other programming languages force you to declare
variables at the beginning of program.
- Python does assign type and it must be used as that type or converted.
- How does python know? String -- in quote marks, INT - no decimal, float - decimal
Lectures Page 5
Input
September-25-09 Reading Ahead
11:33 AM 77-86
91-93
Performing Calculations
+addition
-Subtraction
*Multiplication
/division
In addition we have
** exponent
% remainder
// integer division
31 divided by 8 =
31/8 = 3.875
31%8= 7
31//8 = 3
31.0//8.0= 3.0
31.2 // 4.7
31.2 //4.0
Output:
Each child gets 1.5 bags.
Each child gets 1 bags.
Operator Precedence
3+4*7
1. Exponentiation **
2. Multiplication, division, remainder *, /, % (no order)
3. Addition, subtraction +, -
Lectures Page 6
- What happens if you have an equation with mixed types?
Python 3.1
Integer division
Converting type
Int()
Float()
Str()
Int ("5") = 5
Int(5) = 5
Int (5.9) = 5
Int ("5.9") = error
Int ("Hi") = error
Float("5") = 5
Float(5) = 5
Float(5.9) = 5.9
Float("5.9") = 5.9
Float("hi") = error
Str(5) = '5'
Str ('5') = '5'
Str ('Hi') = 'hi'
Lectures Page 7
Functions
September-25-09
12:13 PM
Simple Functions
- Simpler code
- Code reuse
- Better testing
○ Test each piece individually
- Faster development
- Better for teamwork
○ Team members can work individually
Naming functions
- Essentially the same as for variables
- Can use A to Z, a to z, 0 to 9, _
- No python keywords
- Can't start variable with a number
- No spaces
- Case sensitive
Indentation in python
Lectures Page 8
Passing arguments
September-30-09
11:34 AM
91-99
#########################################
#program to convert from Celsius to Fahrenheit
Average(first,second,third,fourth,fifth)
-
##
If name == 'mary'
Mary<er7
Lectures Page 9
Local Variables
October-02-09
11:35 AM
Local variable - a local variable is created within a function and can only be accessed within that
function.
Def vegas() :
Secret_wife = input ('please enter the name of the woman you secretly married in vegas').strip()
Return
Vegas ()
Print('your secret wife is {0}'.format(secret_wife))
Scope - the part of the grogram from which a variable can be accessed.
- The scope of a local variable is the function in which it was created.
Print (sum)
Sum = 3+5
Def ontario():
Wife = input('please enter the name of your ont wife;).strip()
Print ('your ontario wife is {0}.'.format(wife))
Return wife
Def manitoba():
Wife = input('please enter the name of your manitoba wife').strip()
Print ('your manitoba wife is {0}.'.format(wife))
Return wife
Ontario()
Manitoba()
Ont_wife = ontario()
Manit_wife = manitoba()
Print (ont_wife)
Print (manit_wife)
Program Design
Bottom up design
Lectures Page 10
Program Design
October-05-09
11:33 AM
Program Design
- Break the main problem into smaller problems that need to be solved, then break these down and so
on. This is a "big" picture approach
Bottom up design
- A bunch of functions are written that might be useful for the program. You build up the program from
these pieces.
#########################################
Example(topdown)
Card game war split the deck between two players, each player turns over one card. The higher
card wins and that player takes both cards. If there's a tie, each player deals three cards and then
turns over the fourth card. The highest fourth card wins. The game is over when one player (the
winner) has all the cards
Problem Solving
Write a program that asks the user to enter the monthly costs for the following expenses for a car loan
payment, insurance, gas, oil, tires, and maintenance. The program should then display the total monthly
cost and total annual cost of these expenses
Input
- Ask the user input()
- Define it
- Read in a file
Output
- Print
- Write to a file
Do something
- 6 w's
- What and how
Lectures Page 11
Returning values
October-05-09
12:14 PM Reading ahead PP 113-131
Def gg(kills) :
KDR = kills/deaths
Return (KDR)
KDR = gg(kills)
###############
Global Variables
Global Constants
GRAVITY_CONSTANT = 9.8
`1234567890-=qwertyuiop[]asdfghjkl;'\\zxcvbnm,./!@#$%^&*()_+QWERTYUIOP{}
ASDFGHJKL:"||ZXCVBNM<>?
Lectures Page 12
The IF Statement
October-07-09
11:34 AM
If condition holds
Statement
Statement
If day_of_the_week == 'weekday' :
Statement
Statement
Boolean Expressions
- a statement that is either true or false
- Also can have Boolean variables
If condition holds :
Statement
Else :
Statement
Def grade_result(grade):
If grade > 49 :
Print ('Pass')
Else :
Print ('fail')
Return
Strings
Lectures Page 13
○ Equal ==
○ And not equal != are straight forward
If day == 'Monday'
Print ('class')
If day != 'weekday' :
Print ('sleep in')
Lectures Page 14
If elif else statement
Wednesday, October 14, 2009
11:36 AM
- All the examples we have seen so far have involved a binary choice, only two choices
If condition :
Statement
Statement
Elif condition_2:
Statement
Statement
Else :
Statement
Lectures Page 15
Repetition Structures
Monday, October 19, 2009
11:31 AM
Count-Controlled Loop
- For
While condition :
Statement
Statement
Boolean Condition
while condition :
If it is true, it executes the code. If it is false, it skips them.
- The loop executes at least once if condition is true.
Lectures Page 16
- You must initialize the condition
- It must change in a meaningful way
Total = total + 1
While total > 0
version2
Secret_number = int (input('Enter a secret number'))
Guess = secret_number-1
Whileguess != secret_number
Guess = int(input('please guess a number'))
Print ('you win')
Version3
Secret_number = int(input('please enter a secret number'))
Guess = int(input('please guess a number'))
While guess != secret_number :
Guess = int(input('Guess another number'))
Print ('You win')
Marks_total = 0
Course_num = 0
Courses = 'y'
Lectures Page 17
Infinite Loops
Wednesday, October 21, 2009
12:06 PM
An infinite loop happens when a loop keeps executing and does not stop
- Can happen when :
○ The programmer forgets to change the loop test condition
○ The programmer changes the loop test condition in a way that is wrong
Strings
Word = tent
Letter = t
Letter = e
Indexing
- strings are implicitly indexed in python
- Indexing starts at 0
V(1)a(2)m(3)… etc
Scary_creature ='vampire'
Scary_creature[4]
Scary_creature[-1]
- -1 is the index of the last character
Smiles
-7……..-1
Lectures Page 18
-7……..-1
Halloween
Word[0] returns H
Word [1] returns a
Compare
Word[i-1] and word[i]
Lectures Page 19