Python Worksheet
Python Worksheet
"#$%&
Python
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"#$%!"&''%
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!()*+!,-!.')&$/
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!&')0!)$0!1&2,'%
Introduction
'&#(%)*+#,%&
• a programming language like Java and C++.
! )!3&-4&)552$4!.)$4#)4'!.26'!7)8)!)$0!9::;
• a high-level language that translate a set of instructions into
! )!<24<=.'8'.!.)$4#)4'!,<),!,&)$*.),'!)!*',!->!2$*,&#?,2-$*!2$,-!5)?<2$'!
machine language, which is represented by 0s and 1s.
.)$4#)4'/!1<2?<!2*!&'3&'*'$,'0!@+!A*!)$0!B*;!
Getting Python
-.##,&/0!"#$%&
At home:
You want to download the latest version, which is 2.5.2.
1#0$%2.3
Go to http://www.python.org/download/
C-#!1)$,!,-!0-1$.-)0!,<'!.),'*,!8'&*2-$/!1<2?<!2*!D;E;D;
Assuming you are using Windows, after you have installed it, go to
F-!,-!<,,3GHH111;3+,<-$;-&4H0-1$.-)0H
Start > All > Programs > Python > IDLE.
I**#52$4!+-#!)&'!#*2$4!J2$0-1*/!)>,'&!+-#!<)8'!2$*,)..'0!2,/!4-!,-!K,)&,!L!I..!
In the lab:
M&-4&)5*!L!M+,<-$!L!NOP(;
Go to Start > All Programs > Python 2.5 > IDLE.
'&0#$.04563
F-!,-!K,)&,!L!I..!M&-4&)5*!L!M+,<-$!D;E!L!NOP(;
1
Now try this out!
In the window that appears, you should see the python prompt >>>.
This is asking you to enter python commands. Type in the following to
see what happens.
To display or output:
>>> print "Hello World"
>>> print 'Hello World'
>>> print Hello World
Q1: Why is there an error?
2
>>> type(2.5)
>>> type(“15”)
>>> type(“2.5”)
3
>>> print result
>>> x = raw_input('Please enter a string: ')
>>> print x
>>> name = raw_input("Enter your name here: ")
>>> age = raw_input("Enter your age here: ")
>>> print "Your name is:", name
>>> print "And you are", age
4
More challenges!
You can use loops when you want to repeat a set of instruction
multiple times.
>>> i = 0
>>> while(i < 10):
i=i+1
print i
(Hit Enter twice)
>>> x = 10
>>> while (x > 0):
x=x-1
print x
(Hit Enter twice)
>>> x = 10
>>> while (x != 0):
print x
x=x-1
print "wow, we've counted x down, and now it equals", x
(Hit Enter twice)
5
for loop pseudocode
for item in container:
# action to repeat for each item in the container
else:
# action to take once we have finished the loop.
6
The if statement
Execute a block of statements depending on some condition.
if statement pseudocode
if(expression one):
# Action to take if expression one evaluates True
else:
# Action to take if all expression one evaluates False
>>> i = 8
>>> if(i % 2):
print "Odd Number"
else:
print "Even Number"
(Hit Enter twice)
>>> z = 4
>>> if (z > 70):
print "Something is very wrong"
elif (z < 7):
print "This is normal"
(Hit Enter twice)
>>> i = -8
>>> if(i > 0):
print "Positive Integer"
elif(i < 0):
print "Negative Integer"
7
else:
print "Zero"
(Hit Enter twice)
8
List of Elements
To add elements to a list
>>> list = [] # gives an empty list you can add elements to
>>> list.append(‘a’)
>>> print list
you can also initialize the elements of a list and access each element
>>> list2 = [‘a’, ‘b’, ‘c’]
>>> print list2[0] # in computer science we count from 0
>>> print list2[2] # list2[2] is the 3rd element not the 2nd
>>> print list2[3]
Q5: Explain why there is an error?
Questions
2. Create the same list starting with an empty list and using a loop.
3. Make one change to your code from number 2 to create the list
[0,2,4,6,8].
9
Writing a Program in a File
1. To do so, open any text editor and enter the following four lines in a
file named 'hello.py'. Put the lines on the left-margin-- no tabs or
spaces.
print "hello"
print "world"
name = "jive"
print name
python hello.py
Note that you should enter the above at the operating system prompt,
not the Python prompt. If you're still within the Python interpreter, exit
with control-D.
hello
world jive
Challenge Questions
A: 90 - 100
B: 80 – 90
C: 70 – 80
D: 60 – 70
E: 0 – 60
10
2. Write a for loop to produce the following output:
*
**
***
****
*****
Sample:
Steps:
(Use what you know about dividing integers and floating point
numbers to compute the correct temperature)
Enter a temperature: 68
Convert to (F)ahrenheit or (C)elsius: C
68 F = 20 C
Steps:
11
For example:
if (input == ‘a’)
…
do something
…
else
…
do something else
…
3. Compute the temperature in Fahrenheit or Celsius:
F = (9/5)*C+32
C = (5/9)*(F-32)
12
Media Programming Introduction
Usually you'll use the top window, which is a text editor. You write
the program there, then click 'Load program' to run it.
Tutorial
1. With JES you work with pictures. So the first step is to download an
image from the web into your H: directory. With most browsers, you
can right-click an image and choose "Save Images as" or something
similar.
filename = pickAFile()
pic = makePicture(fileName)
show(pic)
Enter the lines exactly as shown above, then click File > Save
Program. Save in imageSample.py.
3. Run your program by clicking the "Load Program" near the middle
of the JES Window. You (the end-user) will be prompted to choose a
.jpg or other graphic file. Choose an image from one of your folders,
and the program should render the picture. That is all this first
program does.
13
4. Now we'll modify your program and have it change the image, just
as a human might do in Photoshop. For now, let's just draw some text
and a line on our picture. Add the following below the previous code in
your sample.py file:
addLine(pic,0,0,200,200)
addText(pic,100,100,"hey dude”)
repaint(pic)
Do you see the line on the picture? Try different numbers and text for
the parameters. What happens?
writePictureTo(pic,'/home/wolber/pics/out.jpg')
If you're using Windows, you need to put an 'r' in front of the file path.
For instance:
writePictureTo(pic,r"H:\out.jpg")
Add the appropriate line to the bottom of your program, rerun your
program, then go into the folder you specified and see if the new file
has been created and if the image inside it is the modified picture.
14
Calling Functions: Parameters and Return Values
A function does some work for us. We can send a function some data,
and it will perform some task and send us something back.
Consider the function sqrt. A program can send it a number and get
something back:
result = sqrt(16)
When you call a function, you sometimes send it some data that it
needs to do its job. We call such data a parameter. 16 is the
parameter sent to sqrt in the sample above. Parameters are placed in
parenthesis after the function name.
def cube(x):
return x*x*x
result = cube(3)
filename = pickAFile()
pic = makePicture(fileName)
show(pic)
addLine(pic,0,0,200,200)
addText(pic,100,100,"hey dude")
repaint(pic)
15
The makePicture function has one parameter, fileName. You tell
makePicture a fileName, and it loads a picture for you (in memory).
That picture is returned to your program and 'caught' in the variable
pic.
In-Class Worksheet
1. What are the parameters of the other JES function calls above?
Which need to catch a return value?
16
Using Python to Send Email
#Sample program 1
import smtplib
try:
smtpresult = session.sendmail(sender, recipient, msg)
except:
print "failure"
#Sample program 2
import webbrowser
webbrowser.open("http://www.google.com")
print "done..."
Exercises
1. Write a program to prompt the user for a word and print "You
entered: " followed by the word that the user entered.
17