Anda di halaman 1dari 19

BLUE = DEFINITION

Introduction RED = PROBLEM


September-16-09 GREEN = DESCRIPTION
11:31 AM
PURPLE = EXAMPLE

Program - a set of instructions Problem: searching a list


2 parts 2,7,11,15,37,67,71,89
○ Algorithms
 Recipe to solve a problem One algorithm: start at the beginning of the list and go through one element at a time,
○ Data structures looking for the number you want.
 Organize the data Linear Search

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)

- All the computer knows is 0's and 1's


○ Each 0 or 1 is called a bit
○ Eight bits make a byte
○ All the arithmetic operations are done in binary arithmetic

- Any non negative integer can be represented in binary

128 64 32 16 8 4 2 1
1 1 1 1 11 1 1 = 255

To go from a high level language e.g. python to what a computer


understands binary m you need either a compiler (turns file into
exe. You run the executable) or interpreter (executes as it runs)

Lectures Page 1
Writing Programs
September-18-09
11:46 AM

1. Design the program


a. Read the specifications
b. Understand the problem
c. How to approach solution
d. Write the algorithm
2. Write the code
3. Correct syntax errors
a. Syntax
i. Error in way you typed it
b. Logical error
4. Test the program
5. Correct logical errors
a. Doesn't give you the answer you want

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.

What do you need?

1. Prompt user for input


2. Need some variables
3. Way to count the numbers of people registered
4. Close registration after certain number is attained
5. Test to see if 100 is reached
6. Store the infos

Print
- Print is a function in Python 3.0

Print ('Hello world') <-- new python


Print 'hello world' <-- old python

Print is a reserved word or keyword in Python


You cannot use print for another purpose.
34 in python, p18 of text
Three extra reserved word: true, false, none

Lectures Page 2
Comments
September-21-09
11:36 AM

Reading ahead: 49-54

Comments - sometimes the programmer wants to whisper something to the (human) reader. The
interpreter ignores them.

Comments start with this symbol: #


- Comments begin with a #. Each new line if the comment starts with #. You may use # in the middle of
the line.
- The interpreter ignores everything after # to the end of the line.

#program to show comments.


#created by Dynafrom Wang on September 21 09
Print ('Hello World') #this is a first program
#more code here
#Print (name)

Why use comments?

- To explain parts of a program


- To remind yourself of things
- To state something important about the program
- Commenting out sections of code
- The more comments, the better. --write me a novel...

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

Variable Assignment Data


Name Operator
Day = 10
(left) (right)

#program to print the date


#created by Dynafrom Wang on Sept 21, 2009

Month = 'september' #variable name


Day = 21
Year = 2009
Print ('the month is')
Print (month)
Print ('the day is')
Print (day)
Print ('the date is {0}{1},{2}')
Format (month, day, year)

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
'''

Variable Naming Rules

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

What do I do if I have a compound word?

day_of_the_week = Convention, and lower case.


Caps for all constants.

What if I want to change the value in the variable?

Just reassign it

Day =21
Print ('the day is {0},' . format(day))
Day = 23
Print ('the day is {0},' .format(day))

The day is 21.


The day is 23.

- Variable actually have data types


- The python interpreter stores in memory as a particular type.

Int integer 3,9


Float real number 3.14
Str string 'help'
Float()
Str()
Int()

- 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

month = input ('Please enter the moth').strip()


Raw_input <-- textbook

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

#program to do two different divisions


Print ('How many ways can you divide 6 bags of chocolate chips amongst 4 children?')
Bags = 6
Children = 4
Split1 = /64
Split 2 = 2 6//4

Print ('Each child gets {0} bags.'.format (split1))


Print ('Each child gets {0} bags.'.format (split2))

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 +, -

- You can use brackets to change the order


- (POST FIX NOTATION)

Data Type Conversion


What happens if you have an equation with mixed types?

Lectures Page 6
- What happens if you have an equation with mixed types?

Python 3.1
Integer division

a//b is floor (a/b)

Int combined with int => int


Float ... Float => float
Int ... Float => float

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

- Functions are a group of statements in a program that perform a specific task

#program to give an appointment


Def appointment_time (day_of_the_week):
print ('Your apt is on', day_of_the_week)

Print ('indicate what day you want apt')


Day = input('give a day').strip()
appointment_time (day)

- Functions are executed when they are called


- Function syntax in python:

Def function_name (arguments):


Statement
Statement

Why use 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

- python uses little or no punctuation


- But punctuation is useful for signalling where things start and stop
- Python uses indentation
- Most other languages encourage indentation ( it improves readability) but python forces it.
- Statements that belong to the same block are indented by the same amount.

Lectures Page 8
Passing arguments
September-30-09
11:34 AM
91-99

Argument - a piece of data that is passed to the function when it is called

Function name -> Average (num1, num2) <-- arguments

- You can have more than one argument


- The order of the arguments matters

Def student_calculate (name, id_number,mark1, mark2) :

Student_calculate ('john doe', 090000000, 733, 98)

#########################################
#program to convert from Celsius to Fahrenheit

Def convert (celsius) :


Fahrenheit = celsius * 9/5 + 32
Print ('the temperature in Fahrenheit is {0:.2f}'.format(Fahrenheit))
Return
Temp = float(input('please enter the temperature in Celsius').strip())
Convert(temp)

#Program to computer the average of 5 numbers

Def average (m1, m2, m3, m4, m5) :


Total = (m1+m2+m3+m4+m5)/5
Print (total)
return

Print ('this program calculates the average of five numbers.')


First = float (input('Please enter the first number.'))
Second...
Third...
Fourth...
Fifth...

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.

#program with a local variable error

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.

You cannot call a variable until you created it.

Print (sum)

Sum = 3+5

#program that uses a variable name in two functions

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

Top down design

Bottom up design

Lectures Page 10
Program Design
October-05-09
11:33 AM

Program Design

Top down 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.

- Both approaches use modular design

#########################################

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

- What functions do we need?


○ Function to shuffle (randomize)
○ Function to check for end of deck
○ Function to check for war (compare two values)
○ Function to deal with war in situations of <3 cards

Data structure for cards


(impose limits: no more than 4 of each kind)

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

- In python, values are returned via the return statement

Def gg(kills) :
KDR = kills/deaths
Return (KDR)

KDR = gg(kills)

To return several values:

Def gg (kills, deaths)...


..
Return KDR, ownagelevel

###############

KDR, Ownage = gg (kills, deaths)

Global Variables

- Variables that are accessible by any function in the program file

DON'T USE THEM

1) It makes debugging horrendous


a. Difficult to tell where a variable was changed
2) It makes modularity impossible
a. You can't reuse functions if they depend on a global variable
3) Makes it hard to read

Create variables locally and pass them to functions as arguments

Global Constants

- A value in the program that never changes


- All capitals
- Be at beginning

GRAVITY_CONSTANT = 9.8

Don't change it!

`1234567890-=qwertyuiop[]asdfghjkl;'\\zxcvbnm,./!@#$%^&*()_+QWERTYUIOP{}
ASDFGHJKL:"||ZXCVBNM<>?

Lectures Page 12
The IF Statement
October-07-09
11:34 AM

- Decision structure a set of statements that execute under certain circumstances


- Sequences structure - a set of statements that executes in the order they appear
- Control structure - a logical structure that controls the order in which statements execute

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

== <-- comparator or equals


>greater than
<less than
>= greater than or equal
<= less than or equal
!= not equal

- Having one possibility for a choice is rather useless


- We need if-else statement

If condition holds :
Statement
Else :
Statement

# a function to test whether a mark is pass or fail

Def grade_result(grade):
If grade > 49 :
Print ('Pass')
Else :
Print ('fail')
Return

Mark = int (input('grade:').strip())


Print ('your mark was {0}.'.format(mark))
Grade_result(mark)

Strings

- We have looked at comparing numbers but what about strings?


Equal ==

Lectures Page 13
○ Equal ==
○ And not equal != are straight forward

If day == 'Monday'
Print ('class')

If day != 'weekday' :
Print ('sleep in')

- What about greater than or equal?


- Python compares character by character and compares on the basis of ASCII codes
- A to Z are 65-90
- A to z are 97-122

- Note uppercase is different from lower case


- 'a'<'b'

Apple < apple pie

Apple < orange

ApplePie < Apple_Pie

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

Fall Through Algorithm

< 10000 -> ORDINARY


10000-25000 ->SILVER
25000-50000 -> GOLD
>50000 -> PLATINUM

Lectures Page 15
Repetition Structures
Monday, October 19, 2009
11:31 AM

Reading Ahead P-273-280

- Sometimes you want to repeat an action:


○ Enter the names of everyone on a list
○ Add a series of numbers
○ Search through a list looking for a value

- A repetition structure is a set of statements that execute repeatedly (LOOP)

Condition Controlled Loop


- While

Count-Controlled Loop
- For

Condition Controlled Loop


- Executes until the condition is met

While condition :
Statement
Statement

Count Controlled Loop


- Execute a certain number of times

For variable in [value 1, value2, etc]


Statement
Statement

#program to guess a number


Not_found = True
Secret_number = int(input('number?'))

While not_found == True :


Guess = int(input('Guess a number'))
If guess == secret_number :
Print ('win.')
Else
Print ('try again')

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.

Be careful of x <0 or x <= 0

- You must change the condition within the loop


You must initialize the condition

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')

#program to calculate average

Def average *total, no_of_courses) :


Av = float (total/no_of_courses)
Return av

Marks_total = 0
Course_num = 0
Courses = 'y'

While courses == 'y' :


New_mark =int(input('please enter a mark:'))
Marks_total = marks_total + new_mark
Course_num = course_num + 1
Courses = input('another course? y/n').strip())

Course_av = average (marks_total,


Print ('average is {0:.2f}'.format(course_av))

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

- A string is a sequence of characters

Isolating characters in a string

- Iterating over a string with a for loop

For variable in string :


Statement
Statement

Reading Ahead 161-173


#counts number of letters in a word

Word =input ('Please enter a word').strip())


Count = 0

For letter in word


Count = count + 1
Print (count)

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]

String_name [i] #returns the ith character

- You can also index negative numbers

Scary_creature[-1]
- -1 is the index of the last character

Smiles
-7……..-1

Lectures Page 18
-7……..-1

#program to count the number of double letters in a word

Halloween
Word[0] returns H
Word [1] returns a
Compare
Word[i-1] and word[i]

Word = input('Please enter a word').strip())


Index= 0
Double_total = 0
Previous =' '
While index < len(word) :
Current = word[index]
If current == previous :
Double_total =double_total + 1
Previous = current
Index = index + 1
Print ('The number of double letters is {0}.'.format(double_total)

Lectures Page 19