Chapter2: Introduction to programming

Download Report

Transcript Chapter2: Introduction to programming

Media Computation in JES
(Chapter 2)
DM Rasanjalee Himali
JES Functions
• Some JES functions (NOT Python)
• A bunch of functions are pre-defined in JES for
sound and picture manipulations
– pickAFile()
– makePicture()
– makeSound()
– show()
– play()
• Some of these functions accept input values
What to do to show a picture
• 1. Find a file with a picture.
• 2. Pick it.
• 3. Get the bytes from that file into memory
and label it as a type: “picture”
• 4. Show the picture
file = pickAFile()
• Displays list of directories
and files in a window
• Accept no inputs
• Returns a string which is the
name of file that you picked
• This does NOT load the file
into memory
• Python is case sensitive:
– pickafile() or PickAFile() will
not work!
• The pickAFile() function
brings up a ‘file selector
• You’ll choose a file and
hit the ‘Open’ button
• When you pick your file,
the pickAFile() function
notes the ‘path name/
address’ (as a string) of
your file.
Path seperator
File extension
>>> print file
Path to the file
Base file name
Full file name
• We will stick to JPEG and WAV files to avoid too
much complexity.
File Extension
JPEG file
Contains a picture
WAV file
Contains sounds
Showing a Picture
• pickAFile() does not load file into the memory.
• To load the file into the memory we should tell JES to
read the file and make a picture from it using function
• makePicture requeres one parmeter: the file name.
>>> pic = makePicture(file)
Picture, filename F:\UNG\Python\mediasourcespy2ed\mediasources\beach.jpg height 480 width 640
• Now we made a picture with hight 480 and width 640
• How do we see the picture?
• To see the picture
you made we need
another function:
• show takes a
parameter : picture
(referenced by pic
in our example)
• To summarize, the code:
>>>file = pickAFile()
>>>pic = makePicture(file)
• Another way to do this is to do it all at once
because output from one function can be
used as input to another function:
>>> show(makePicture(pickAFile)))
• What is the return type of function show?
• Try printing:
>>> print show(pic)
• The output is none, indicating that the
function does not return an output.
• Functions in Python does not have to return a
Playing a Sound
• We can replicate the entire process of
showing picture with sounds.
– We still use pickAFile() to find the file and get its
file name. This time we pick a file with .wav
– makeSound(filename) creates and returns a
sound object, from the WAV file at the filename
– play(sound) makes the sound play (but doesn’t
wait until it’s done). It takes file name as input.
– blockingPlay(sound) waits for the sound to finish
• Here are the same steps we saw with making
pictures, this time used to play sound:
>>>file = pickAFile()
>>> print file
>>> sound = makeSound(file)
>>> print sound
Sound file: F:\UNG\Python\mediasourcespy2ed\mediasources\helloWorld.wav number of samples: 44033
>>> play(sound)
• Download the mediasouce zip file at :
• Extract it to a folder. This contains sample .jpg,
.wav etc files you can work with.
• Try the previous code in both .wav and .jpg
Naming values
• As we saw in previous examples, we name
values/data using = operator (E.g. file, pic)
• Computers do not remember things unless we
name them
• Creating a name for a value is called “defining a
• A variable is a unit of data with an identifier,
which is held in your computer's memory
• It can be changed by putting a new value into it
or modifying the value that is already there.
• We can check the value of a variable using print:
>>>myVariable = 12
>>>print myVariable
>>>anotherVariable = 34.5
>>>print anotherVariable
>>>myName = “Mark”
>>>print mayName
• We can use names more than once:
>>>print myVariable
>>> myVariable = “Hello”
>>> print myVariable
• The binding (or the association) between the
names and the data only exists until
– (a) the name gets assigned to something else OR
– (b) you quit JES
• What is the output of the following?
>>>myVariable = 12
>>>print myVariable*4
>>>myOtherVariable = “12”
>>>print myOtherVariable
• Data have encodings/types. How data act in
expressions depend on their types. E.g. integer 12 and
the string 12 act differently for multiplication.
Choosing Good Identifiers
• Identifiers are the names used to identify
things in your code.
• An identifier is just a name label
• So it could refer to more or less anything
including commands
Python Keywords
• The following words are the keywords, which form the basis
of the Python language.
• You are not allowed to use these words to name your
variables, because these are the core commands of Python.
Naming Rules
• Variable names must begin with either a letter or an
• Although they can contain numbers, they must not
start with one.
• You should not use anything other than letters,
numbers, or underscores to identify your variables.
• Python is generally case-sensitive, which means that
lowercase and uppercase letters are treated as being
different characters; therefore, myvariable,
MYVARIABLE, and MyVariable are interpreted as
completely different entities.
• We can assign names(i.e. variable names) to the
results of a functions.
• E.g.
>>> file = pickAFile()
>>> print file
>>>pic = makePicture(file)
>>> print pic
Picture, filename F:\UNG\Python\mediasourcespy2ed\mediasources\barbara.jpg height 294 width 222
• Note: its not necessary to use print every time we
execute something.
Making a program
• Defining functions:
– Just like naming values, we can name programs.
– We can name a series of commands and use the
name to whenever we want the commands to be
– In Python, the name we define is called a
– A program in Python is a collection of functions
that perform a useful task
• You need to use the keyword def to define a
new function.
• Syntax:
def <functionName> ( <input list seperated by commas>):
• Then we create a collection of commands by
defining a block:
– The list of commands to be executed when
function is called are listed after this line one after
the other (indented to show they belong to this
Saving and Executing Your Programs
• The interactive interpreter makes it possible
to test solutions and to experiment with the
language in real time.
• However, everything you write in the
interactive interpreter is lost when you quit.
• What you really want to do is write programs
that both you and other people can run.
• First, you need a text
editor. If you are already
using JES, you’re in luck:
JES provides a nice text
editor area for you to
write our programs.
• Simply create a new
editor window with File
➤ New Program. Whew!
• In CSCI1301 you’ll put
your instructions in the
definition of a function
when writing programs.
• Now select File ➤ Save
Program As to save your
program (which is, in
fact, a plain text file).
• Be sure to put it
somewhere where you
can find it later on.
• Give your file any
reasonable name, such
as The .py
ending is important.
• Got that? Don’t close
the window with your
program in it. If you did,
just open it again (File
➤Open Program).
• Now you need to load
by pressing button
“Load Program” .
• You can execute/run
your program by calling
the method hello in
command window:
• Sometimes, you’ll have a clear purpose for the
function, in which case you can name the
function accordingly, like “triArea()” or
“reverseText()”, but for experimenting or other
general purposes, you can call it “main()”, as in
“main function”.
• E.g.
def main():
print "Hello world!"
• Notice also that the print statement is indented.
def main():
print "Hello world!"
• In Python, indenting specifies the “scope” of different
chunks of your code.
• Consider it this way: everything indented after a first,
unindented (or less indented) line ‘belongs’ to that line.
• So above, the print statement belongs to the definition of
the function called ‘main()’.
• If you wanted ‘main()’ to accomplish multiple things, they’d
all have the same amount of indent as the print statement.
• Write a program to allow user
to pick a picture and show it. Call the function
that does this pickAndShow.
• Answer:
def pickAndShow():
myFile = pickAFile()
myPict = makePicture(myFile)
Box indicates a block in program
You will know your indentation is
Right when all the commands you
expect to be in the block is in the box
• Now save your program and load it using the
“Load Program” button.
• Now you can call it in your command area:
• We can similarly define our second program to
pick and play sound.
The Most Common JES Bug:
Forgetting to Load
 Your function does NOT
exist for JES until you load
 Before you load it, the
program is just a bunch of
 Loading encodes it as an
executable function
 Save and Save As
 You must Save before
 You must Load before you
can use your function
An “Unloaded” function
doesn’t exist yet.
What if you forget your variable
names? showVars()
• Write a program to allow user
to pick a sound and play it. Call the function
that does this pickAndPlay.
• Answer:
def pickAndPlay():
myFile = pickAFile()
mySound = makeSound(myFile)
Show a specific picture
def showPicture():
myFile = “c:/mediasources/barbara.jpg”
myPict = makePicture(myFile)
What to do about Windows
• Python doesn’t like you to use “\” in
like “C:\mediasources\barbara.jpg”
• What to do?
– Option #1: Put r in front of Windows filenames:
– Option #2: Use forward slashes. Python will
translate it for you:
A function that takes input
def playNamed(myfile):
mysound = makeSound(myfile)
def showNamed(myfile):
mypict = makePicture(myfile)
How do you call such a function?
What functions do you need? What
should be their input?
In general, have enough to do what
you want, easily, understandably,
and in the fewest commands.
We’ll talk more about what that
means later.
• Write a program with a function playAndShow
that plays a sound and shows a picture at the
same time. The file names for sound file and
picture files should be input parameters to the
def plaAndShow(sFile, pFile)
mySound = makeSound(sFile)
myPict = makePicture(pFile)
What can go wrong?
• Did you use the exact same names (case,
• All the lines in the block must be indented,
and indented the same amount.
• Variables in the command area don’t exist in
your functions, and variables in your functions
don’t exist in the command area.
• The computer can’t read your mind.
– It will only do exactly what you tell it to do.
• Try them out for yourself. Try to replicate
them. Understand them
• To understand a program means that you
know why each line is there.
• You will encounter all the simple-butconfusing errors early—BEFORE you are
rushing to get homework done!!