Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
65 views

Python Basic

- Python is an interpreted language, meaning code is executed line by line without compiling. It is useful for short to medium sized projects and as a scripting language. - To use Python, it needs to be installed from python.org on Windows or via the package manager on Linux. On Mac it is pre-installed. Code is run by typing commands or running files. - Python is untyped so variables can change types during execution. It also uses indentation rather than braces to define code blocks.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Python Basic

- Python is an interpreted language, meaning code is executed line by line without compiling. It is useful for short to medium sized projects and as a scripting language. - To use Python, it needs to be installed from python.org on Windows or via the package manager on Linux. On Mac it is pre-installed. Code is run by typing commands or running files. - Python is untyped so variables can change types during execution. It also uses indentation rather than braces to define code blocks.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 139

>>> Python Basics

• Interpreted
• Not compiled like Java
• This means: type commands and see
results
• Targeted towards short to medium
sized projects
• Useful as a scripting language

A whaa?
script – short Compile Runtime Compute
program meant for Code
r Env r
one-time use.
Compute
Code Interpreter
r
>>> Getting it Going
Windows Mac OSX Linux

1) Download Python 1) Python is already 1) Chances are you


from python.org. installed. already have
2) Run 'python' 2) Open a terminal Python
using the run and run python installed. To
command. or run Idle check run
-or- from finder. python from the
Run Idle from terminal.
the Start Menu. 2) If not, install
python through
Note: For step by step your
installation instructions,
follow those provided on the distribution's
course web site. Click on package system.
Python on the right hand side
and follow the “Python
Installation Instructions”
>>> Topic Review
* printing - System.out.println();
* methods – public static void <name>() ...

Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 System.out.println("Hello world!");
4 }
5 } Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 hello();
4 }
5 public static void hello(){
6 System.out.println("Hello world!");
7 }
8 }
>>> Missing Main

Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 System.out.println("Hello world!");
4 }
5 }

The entire file is hello.py


interpreted as if it 1 print "Hello world!"
2
was typed into the 3
4
interpreter. This 5
makes it easy to
write scripts with
Python.
>>> Printing
Hello.java
1 public class Hello {
2 public static void main(String[] args){
3 System.out.println("Hello world!");
4 System.out.println();
5 System.out.println("Suppose two swallows carry it
6 together.");
7 }
8 }

Escape sequences: hello.py


* \t – tab 1 print "Hello world!"
* \n – new line 2 print
* \" - " 3 print "Suppose two swallows carry it
* \\ - \ together."
4
>>> Methods
Hello.java Structure:
1 public class Hello {
2 public static void def <method name>():
3 main(String[] args){ <statement>
4 hello(); <statement>
5 } <statement>
6 public static void hello(){ ...
7 <statement>
8 System.out.println("Hello \"wo
rld\"!"); Note: Python does not
}
hello.py
}
have a main method.
1 def hello(): However, methods must
2 print
3 "Hello \"world\"!"
be defined first.
4 Calls to methods can
5 #main then be made. This is
hello()
similar to having a
“main” section of code.
It is good practice to
label this section of
>>> Whitespace
Unlike in Java, in Python whitespace (think tabs and spaces) matters.
Instead of using braces ({}) to designate code blocks, Python uses the
indentation. This was done to promote readable code. In Java you may
or may not indent and it will work. In Python you must indent.
Hello.java
1 public class Hello {
2 public static void main(String[] args){
3
4 System.out.println(“Hello \"world\"!”);
5 }
}

hello.py
1 def hello():
2 print
3 "Hello \"world\"!"
4
hello()
>>> Example 1
Example: Write a method that
produces the following
output.
e are the Knights Who Say... "Nee!"
Nee! Nee! Nee!)

O! Not the Knights Who Say "Nee"...

e are the Knights Who Say... "Nee!"


Nee! Nee! Nee!)
>>> Example 1
Solution:

def knights():
print "We are the Knights Who Say... \"Nee!\""
print "(Nee! Nee! Nee!)"
print

def poorSouls():
print "NO!\t Not the Knights Who Say \"Nee\"..."
print

knights()
poorSouls()
knights()
>>> Example 2
Example: Write a method that
produces the following
output.
______
/ \
/ \
\ /
\______/
\ /
\______/
+--------+
______
/ \
/ \
| STOP |
\ /
\______/
______
/ \
/ \
+--------+
>>> Example 2
Example: Write a method that def egg(): def top():
produces the following top() print " ______"
output.
______ bottom() print " / \
/ \ print print "/
/ \
\ /
\______/ def cup(): def bottom():
bottom() print "\\
\ / line() print " \\______
\______/ print
+--------+
def line():
______ def stop(): print "+--------
/ \ top()
/ \ print "| STOP |"
egg()
| STOP | bottom() cup()
\ /
\______/ print stop()
hat()
______ def hat():
/ \ top()
/ \ line()
+--------+
print
>>> Types
Python cares very little about types.
Java pytho
In Java, one must declare a variable
with a particular type and maintain 178 int n
int
that type throughout the existence of 175.0 double float
that variable. In other words, ints “wow” String str
can be only stored in places 'w' char str
designated for ints, same for doubles True boolean bool
etc.

This is not the case in Python.


Python does not care about types
until the very last moment. This
last moment is when values are used
in certain ways, such as
concatenation of strings.
>>> String concatenation
Like Java, we can concatenate strings using a “+”. Unlike Java,
when a number has to be concatenated with a string in python, you
need to explicitly perform the conversion to a string using the
str() function because it hasn’t made sure that the types match
before run time.

>>> "Suppose " + 2 + " swallows carry it together."


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> "Suppose " + str(2) + " swallows carry it together."
'Suppose 2 swallows carry it together.'
>>> Python expressions
Python is very similar to Java in
the way that it handles expressions
such as:

 + - * / %
 Integer division – rounds down to
nearest int
 Precedence – same rules
 Mixing types – numbers change to
keep precision
 Real numbers are kept as “floats”
or floating point numbers
>>> Differences in expressions
There are a few things that
differ between Python and
Java, such as: >>> "Hello!"*3
'Hello!Hello!Hello!'
You can multiply strings in >>> x = 1
>>> x += 1
python! >>> print x
2
There are no increment
operators in python (++, --)
so we have to use -= and +=
>>> Variables
As we said earlier, Python cares
less about types. When we create
a variable in Python, the type of
the variable doesn’t matter. As a expressions.py
result, in Python, creating a 1 x = 2
variable has the same syntax as 2 x += 1
setting a value to a variable. 3 print( x)
Variables.java
1 ... 4 x = x * 8
2 5 print (x)
int x = 2; 6
3 x++;
4 7 d = 3.0
System.out.println(x); 8 d /= 2
5 x = x * 8;
6 9 print (d)
System.out.println(x); 10
7
11 s = "wow"
8 double d = 3.0; 12 print (s)
9 d /= 2;
10 13
System.out.println(d); 14
11
15
16
>>> Constants
Continuing Python's free spirited
ways, it has much less restrictions constants.py
than Java. Because of this, 1 SIZE = 2
constants are possible but not in a 2 x = 10 * SIZE
commonly used manner. Instead, 3 print x
we'll designate constants in Python 4
solely by the variable 5 # main
capitalization. 6 …
We do need to write the constants
at the top of our program so that
every function can see them!
>>> print 123
Fixed values such as numbers, 123
letters, and strings are called >>> print 98.6
“constants” - because their value 98.6
does not change >>> print 'Hello world'
Numeric constants are as you Hello world
expect
String constants use single-
quotes (')
or double-quotes (")
Variables
A variable is a named place in the memory where a
programmer can store data and later retrieve the data
using the variable “name”
Programmers get to choose the names of the
variables
You can change the contents of a variable in a later
statement

x = 12.2 x 12.2100
y = 14
x = 100 y 14
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores

• Case Sensitive
• Good: spam eggs spam23 _speed
• Bad: 23spam #sign var.12
• Different: spam Spam SPAM
Reserved Words

• You can not use reserved words as variable names /


identifiers
and del for is raise
assert elif from lambda
return
break else global not try
class except if or while
continue exec import pass
yield
def finally in print
Sentences or Lines
Assignment Statement
x = 2
Assignment with
x = x + 2
expression
print x
Print statement

Variable Operator Constant Reserved Word


Assignment Statements

• We assign a value to a variable using the assignment


statement (=)
• An assignment statement consists of an expression
on the right hand side and a variable to store the
result

x = 3.9 * x * ( 1 - x
A variable is a memory
location used to store a
x 0.6
value (0.6).

0.6
0.6

x = 3.9 * x * ( 1
0.4

Right side is an expression. 0.93


Once expression is evaluated,
the result is placed in
(assigned to) x.
A variable is a memory
location used to store a
value. The value stored
in a variable can be
x 0.6 0.93
updated by replacing the
old value (0.6) with a
new value (0.93).

x = 3.9 * x * ( 1

Right side is an
expression. Once
expression is evaluated, 0.93

the result is placed in


(assigned to) the
variable on the left
side (i.e. x).
Numeric Expressions

Because of the lack of Operator Operation


mathematical symbols on + Addition
computer keyboards - we use
Subtractio
“computer-speak” to express -
n
the classic math operations
Multiplicat
Asterisk is multiplication *
ion
Exponentiation (raise to a
/ Division
power) looks different from
in math. ** Power

% Remainder
Numeric Expressions
>>> xx = 2 >>> jj = 23
>>> xx = xx + 2>>> kk = jj % 5 Operato Operatio
r n
>>> print xx >>> print kk
+ Addition
4 3
Subtractio
>>> print 4 ** 3
>>> yy = 440 * 12 -
n
64
>>> print yy *
Multiplica
tion
5280
/ Division
>>> zz = yy / 1000 4 R 3
>>> print zz 5 23
** Power

5 20 %
Remainde
r

3
Order of Evaluation

When we string operators together - Python must


know which one to do first
This is called “operator precedence”
Which operator “takes precedence” over the others

x = 1 + 2 * 3 - 4 / 5 ** 6
Operator Precedence Rules
• Highest precedence rule to lowest precedence rule
• Parenthesis are always respected
• Exponentiation (raise to a power)
• Multiplication, Division, and Remainder
• Addition and Subtraction
• Left to right Parenthesis
Power
Multiplicatio
Addition
Left to Right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11 1 + 8 / 4 * 5
>>>
Parenthesis 1 + 2 * 5
Power
Multiplication
Addition 1 + 10
Left to Right
11
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print x
11 1 + 8 / 4 * 5
>>>

Note 8/4 goes before 1 + 2 * 5


4*5 because of the
left-right rule.

Parenthesis 1 + 10
Power
Multiplication
Addition 11
Left to Right
Operator Precedence
Parenthesis
Power
• Remember the rules top to bottom Multiplication
• When writing code - use parenthesis Addition
Left to Right
• When writing code - keep mathematical expressions
simple enough that they are easy to understand
• Break long series of mathematical operations up to
make them more clear

Exam Question: x = 1 + 2 * 3 - 4 / 5
Python Integer Division is Weird!
>>> print 10 / 2
• Integer division truncates
5
• Floating point division >>> print 9 / 2
produces floating point 4
numbers >>> print 99 / 100
0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
This changes in Python 3.0
Mixing Integer and Floating
>>> print 99 / 100
• When you perform an 0
operation where one
operand is an integer
>>> print 99 / 100.0
and the other operand0.99
is a floating point the>>> print 99.0 / 100
result is a floating 0.99
point >>> print 1 + 2 * 3 / 4.0
• The integer is -2.5
converted to a floating>>>
point before the
operation
What does “Type” Mean?
In Python variables,
literals, and constants
have a “type”
Python knows the >>> ddd = 1 + 4
difference between >>>an print ddd
integer number and a5
string >>> eee = 'hello ' + 'th
For example “+” means >>> print eee
hello
“addition” if something is there
a number and
“concatenate” if
something is a string concatenate = put together
>>> eee = 'hello ' +
'there'
Type Matters >>> eee = eee + 1
Traceback (most recent
Python knows what “type” call last):
File "<stdin>", line
everything is 1, in <module>
Some operations are TypeError: cannot
concatenate 'str' and
prohibited 'int' objects
You cannot “add 1” to a >>> type(eee)
<type 'str'>
string >>> type('hello')
We can ask Python what <type 'str'>
type something is by >>> type(1)
<type 'int'>
using the type() function. >>>
Several Types of Numbers
>>> xx = 1
• Numbers have two main types >>> type (xx)
• Integers are whole numbers: - <type 'int'>
14, -2, 0, 1, 100, 401233 >>> temp = 98.6
• Floating Point Numbers have >>> type(temp)
decimal parts: -2.5 , 0.0, 98.6, <type 'float'>
14.0 >>> type(1)
• There are other number types <type 'int'>
- they are variations on float >>> type(1.0)
and integer <type 'float'>
>>>
Type Conversions
>>> print float(99) / 100
0.99
• When you put an
>>> i = 42
integer and floating
>>> type(i)
point in an expression
<type 'int'>
the integer is implicitly
>>> f = float(i)
converted to a float
>>> print f
• You can control42.0
this
with the built in>>> type(f)
<type 'float'>
functions int() and
float() >>> print 1 + 2 * float(3) / 4
-2.5
>>>
>>> type(sval)
<type 'str'>
String >>> print sval + 1
Traceback (most recent
Conversions call last):
File "<stdin>", line
1, in <module>
• You can also use TypeError: cannot
int() and float() to concatenate 'str' and
convert between 'int'
>>> ival = int(sval)
strings and integers >>> type(ival)
• You will get an error <type 'int'>
if the string does not >>> print ival + 1
124
contain numeric >>> nsv = 'hello bob'
characters >>> niv = int(nsv)
Traceback (most recent
call last):
File "<stdin>", line
1, in <module>
ValueError: invalid
User Input
• We can instruct
Python to pause and
read data from the
user using the
raw_input function
• The raw_input nam = raw_input(‘Who are you?
print 'Welcome', nam
function returns a
string

Who are you? Chuck


Welcome Chuck
Converting User Input
• If we want to read a
number from the
inp = raw_input(‘Europe floor
user, we must usf = int(inp) + 1
convert it from a print 'US floor', usf
string to a number
using a type
conversion function
• Later we will deal Europe floor? 0
with bad input data US floor 1
Comments in Python
• Anything after a # is ignored by Python
• Why comment?
• Describe what is going to happen in a sequence of code
• Document who wrote the code or other ancillary
information
• Turn off a line of code - perhaps temporarily
# Get the name of the file and open it
name = raw_input('Enter file:')
handle = open(name, 'r')
text = handle.read()
words = text.split()

# Count word frequency


counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1

# Find the most common word


bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count

# All done
print bigword, bigcount
String Operations

Some operators apply to


strings >>> print 'abc' + '123’
+ implies “concatenation” Abc123
* implies “multiple >>> print 'Hi' * 5
concatenation” HiHiHiHiHi
 >>>
Python knows when it is
dealing with a string or a
number and behaves
appropriately
Mnemonic Variable Names
Since we programmers are given a choice in how
we choose our variable names, there is a bit of
“best practice”
We name variables to help us remember what we
intend to store in them (“mnemonic” = “memory
aid”)
This can confuse beginning students because well
named variables often “sound” so good that they
must be keywords

http://en.wikipedia.org/wiki/Mnemonic
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print x1q3p9afd print c

hours = 35.0
What is rate = 12.50
this code pay = hours * rate
doing? print pay
Exercise

Write a program to prompt the


user for hours and rate per hour
to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Summary
• Type
• Resrved words
• Variables (mnemonic)
• Operators
• Operator precedence

• Integer Division
• Conversion between types
• User input
• Comments (#)
n = 5
Repeated Steps
No Yes
Program:
n > 0 Output:
? n = 5
5
while n > 0 :
4
print n
print n n = n – 1
3
2
print 'Blastoff!'
1
print n
Blastoff!
n = n -1 0

print Loops (repeated steps) have


'Blastoff
' iteration variables that
change each time through a
loop. Often these iteration
variables go through a
n = 5

No
n > 0
Yes
An Infinite Loop
?
print
'Lather' n = 5
print
while n > 0 :
'Rinse' print 'Lather’
print 'Rinse'
print print 'Dry off!'
'Dry
off!'
What is wrong with this loop?
n = 0

No
n > 0
Yes
Another Loop
?
print
'Lather' n = 0
print while n > 0 :
'Rinse'
print 'Lather’
print 'Rinse'
print
'Dry
print 'Dry off!'
off!' What does this loop do?
Breaking Out of a Loop
The break statement ends the current loop and jumps
to the statement immediately following the loop
It is like a loop test that can happen anywhere in the
body of the loop
while True: > hello there
line = raw_input('> hello
') there
if line == 'done' : > finished
break finished
> done
print line Done!
print 'Done!'
Breaking Out of a Loop
The break statement ends the current loop and jumps
to the statement immediately following the loop
It is like a loop test that can happen anywhere in the
body of the loop
while True:
line = raw_input('> ') > hello there
if line == 'done' : hello there
> finished
break Finished
print line > done
print 'Done!' Done!
while True: No Yes
line = raw_input('> ') True
if line == 'done' : ?
break
print line ....
print 'Done!'

break

...

print
://en.wikipedia.org/wiki/Transporter_(Star_Trek)
'Done'
Finishing an Iteration with continue
The continue statement ends the current iteration and
jumps to the top of the loop and starts the next
iteration
while True:
line = raw_input('> ')
> hello there
if line[0] == '#' hello
: there
continue > # don't print thi
if line == 'done' > print this!
: break print this!
print line > done
print 'Done!' Done!
Finishing an Iteration with continue
The continue statement ends the current iteration and
jumps to the top of the loop and starts the next
iteration
while True:
line = raw_input('> ') > hello there
if line[0] == '#' : hello there
continue > # don't print this
if line == 'done' : > print this!
break print this!
print line > done
print 'Done!' Done!
No
True Yes
?
while True:
line = raw_input('> ’) ....
if line[0] == '#' :
continue
if line == 'done' : continu
break e
print line
print 'Done!'
...

print
'Done'
Indefinite Loops
While loops are called "indefinite loops" because
they keep going until a logical condition becomes
False
The loops we have seen so far are pretty easy to
examine to see if they will terminate or if they will
be "infinite loops"
Sometimes it is a little harder to be sure if a loop
will terminate
Definite Loops
Quite often we have a list of items of the lines in a
file - effectively a finite set of things
We can write a loop to run the loop once for each of
the items in a set using the Python for construct
These loops are called "definite loops" because they
execute an exact number of times
We say that "definite loops iterate through the
members of a set"
A Simple Definite Loop

5
4
or i in [5, 4, 3, 2, 3 1] :
print i 2
rint 'Blastoff!' 1
Blastoff!
A Definite Loop with Strings
ends = ['Joseph', 'Glenn', 'Sally']
friend in friends :
print 'Happy New Year:', friend
nt 'Done!'
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
No A Simple Definite Loop
Yes
Done Move i 5
? ahead 4
3
for i in [5, 4, 3, 2, 2 1] :
1
print i print i Blastoff!
print 'Blastoff!'

print
'Blast
off!' Definite loops (for loops) have explicit
iteration variables that change each time
through a loop. These iteration variables
move through the sequence or set.
Looking at In...
 The iteration variable
“iterates” though the
sequence (ordered Five-element sequence
Iteration variable
set)
 The block (body) of
code is executed
once for each valuefor i in [5, 4, 3, 2, 1] :
in the sequence print i
 The iteration variable
moves through all of
the values in the
sequence
No
Yes
Done Move i
? ahead
• The iteration variable
“iterates” though the sequence
print i (ordered set)

• The block (body) of code is


executed once for each value
in the sequence

• The iteration variable moves


through all of the values in
the sequence

for i in [5, 4, 3, 2, 1]
: print i
i = 5
No
print i
Yes
Done Move i i = 4
? ahead
print i
print i
i = 3

print i

i = 2
for i in [5, 4, 3, 2, 1] :
print i print i

i = 1

print i
Definite Loops
Quite often we have a list of items of the lines
in a file - effectively a finite set of things
We can write a loop to run the loop once for
each of the items in a set using the Python for
construct
These loops are called "definite loops"
because they execute an exact number of times
We say that "definite loops iterate through the
members of a set"
Making “smart” loops

The trick is “knowing” Set some


variables to
something about the initial values
whole loop when you are for thing in data:

stuck writing code that Look for


something or do
only sees one entry at a something to
time each entry
separately,
updating a
variable.
Look at the
variables.
Looping through a Set

$ python basicloop.
Before
'Before' 9
41 15] :
hing in [9, 41, 12, 3, 74,
rint thing 12
'After' 3
74
15
After
Counting in a Loop
zork = 0 $ python countloop.p
print 'Before', zork Before 0
for thing in [9, 41, 12, 1 9
3, 74, 15] : 2 41
zork = zork + 1 3 12
print zork, thing 4 3
print 'After', zork 5 74
6 15
After 6

To count how many times we execute a loop we introduce a


counter variable that starts at 0 and we add one to it each
time through the loop.
Summing in a Loop
$ python
countloop.py
ork = 0 Before 0
rint 'Before', zork 9 9
or thing in [9, 41, 12, 3, 74, 50
15]41:
zork = zork + thing 62 12
print zork, thing 65 3
rint 'After', zork 139 74
154 15
After 154

To add up a value we encounter in a loop, we introduce a sum


variable that starts at 0 and we add the value to the sum each
time through the loop.
count = 0
Finding
sum = 0
the Average in a Loop
print 'Before',
count, sum $ python averageloop.
for value in [9, 41,Before 0 0
12, 3, 74, 15] : 1 9 9
count = count + 2 50 41
1 3 62 12
sum = sum + 4 65 3
value
5 139 74
print count,
sum, value 6 154 15
print 'After', After 6 154 25
count, sum, sum /
An count
average just combines the counting
and sum patterns and divides when the loop is done.
Filtering in a Loop

nt 'Before’
value in [9, 41, 12, 3, 74,$ 15]
python
: search1.py
if value > 20: Before
print 'Large number',value
Large number 41
nt 'After'
Large number 74
After

We use an if statement in the loop to


catch / filter the values we are
looking for.
Search Using a Boolean Variable
d = False
t 'Before', found $ python search1.py
Before False
value in [9, 41, 12, 3, 74, 15] :
False 9
f value == 3 : False 41
found = True False 12
print found, value True 3
t 'After', found True 74
True 15
After True

If we just want to search and know if a value was found - we use a


variable that starts at False and is set to True as soon as we find
what we are looking for.
Finding the smallest value
llest = None $ python smallest.py
nt 'Before’ Before
value in [9, 41, 12, 3, 74,9 15]
9 :
if smallest is None : 9 41
smallest = value 9 12
elif value < smallest : 3 3
smallest = value 3 74
print smallest, value 3 15
nt 'After', smallest After 3

We still have a variable that is the smallest so far. The first


time through the loop smallest is None so we take the first value
to be the smallest.
The "is" and "is not" Operators
smallest = None
print 'Before’
for value in [3, 41, Python has an "is"
12, 9, 74, 15] : operaror that can be
if smallest is used in logical
None :
smallest = expressions
value Implies 'is the same as'
elif value < Similar to, but stronger
smallest : than ==
smallest =
'is not' also is a logical
value
print smallest, operator
value
print 'After',
Summary
While loops (indefinite)
Infinite loops
Using break
Using continue
For loops (definite)
Iteration variables
Largest or smallest
>>> Python's For
Unlike Java's for loop,
Python's for loop loops
over elements in a
sequence. To loop over a
certain sequence of
integers use the range()
function. Later we will for.py
learn objects that we can 1 for i in range(4): # (end)
use a for loop to go 2 print i
through all of the 3
elements. 4 for i in range(1,4): # (start,end)
5 print i
6
7 for i in range(2,8,2): #
8 (start,end,step_size)
9 print i
10
11 # for <name> in range([<min>,] <max>
12 [,<step>]):
# <statements>
>>> Complex Printing
Sometimes more complex output is needed.
To produce output but not go to the next line, just write a
comma after the last quotes. This adds whitespace, so sometimes
you need “sys.stdout.write()” which just writes what is in the
quotes. You also have to import “sys”!

Hello.java
1 System.out.print("Hello world! ")
2 System.out.print("This will all be")
3 System.out.println(" on the same line.")
4
hello2.py
1 import sys
2
3 sys.stdout.write("Hello world! "),
4 print "This will all be",
5 print " on the same line."
>>> Nested loops
In Python, a lot of the time we
can do nested loops in a much 5
more straightforward way using 44
string multiplication. 333
2222
11111

Nested.java
nested1.py
1 for (int i = 1; i <= 5; i++) {
2 for (int j = 1; j <= (5 - 1 for i in range(5,0,-1):
3 i); j++) { 2 print " " * (i-1)
4 System.out.print(" "); 3 + str(i)*(6-i)
5 }
6 for (int k = 1; k <= i; k+
7 +) { nested2.py
8 System.out.print(i);
9 1 import sys
}
2 for i in range(5,0,-
System.out.println();
3 1):
}
4 sys.stdout.write("
5 " * (i-1))

sys.stdout.write(str(i)*(6-
>>> Mirror
// Marty Stepp, CSE 142, Autumn 2007
// This program prints an ASCII text figure that
// looks like a mirror.
// This version uses a class constant to make the figure resizable.
public class Mirror2 {

scott @ yossarian ~ $ python public static final int SIZE = 4; // constant to change the figure size

public static void main(String[] args) {

mirror.py
#================#
line();
topHalf();
bottomHalf();
line();
| <><> | }

// Prints the top half of the rounded mirror.


| <>....<> | public static void topHalf() {
for (int line = 1; line <= SIZE; line++) {

| <>........<> |
// pipe
System.out.print("|");

|<>............<>| // spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");

|<>............<>| }

// <>

| <>........<> | System.out.print("<>");

// dots .
| <>....<> | for (int j = 1; j <= 4 * line - 4; j++) {

}
System.out.print(".");

| <><> | // <>

#================#
System.out.print("<>");

// spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
}

// pipe
System.out.println("|");
}
}

// Prints the bottom half of the rounded mirror.


public static void bottomHalf() {
for (int line = SIZE; line >= 1; line--) {
// pipe
System.out.print("|");

// spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
}

// <>
System.out.print("<>");

// dots .
for (int j = 1; j <= 4 * line - 4; j++) {
System.out.print(".");
}

// <>
System.out.print("<>");

// spaces
for (int j = 1; j <= -2 * line + (2 * SIZE); j++) {
System.out.print(" ");
>>> Parameters
Parameters are easy in
Python once you know Java's.
Simply remove all types
from the method header and
do the normal conversion.
PrintSum.java
1 public static void printSum(int x, int y)
2 {
3 System.out.println(x + y);
4 }

print_sum.py
1 def print_sum(x, y):
2 print(str(x + y))
3
4 print_sum(2, 3)
>>> Parameters Example

*************
*******
***********************************
**********
* *
**********
*****
* *
* *
*****
>>> Example Solution
def draw_line(num):
print "*" * num

def draw_box(width, height):


draw_line(width)
for i in range(height-2):
print "*" + " " * (width-2) + "*"
draw_line(width)
#main
draw_line(13)
draw_line(7)
draw_line(35)
draw_box(10,3)
draw_box(5,4)
>>> Defaults
Unlike Java, Python's parameters can have default
values to use when one is not given.

print_range.py
1 def print_range(start=1, end=1, interval=1, sep="
2 "):
3 for i in range(start, end, interval):
4 print str(i) + sep,
5 print end
6
7 print range(0,7)
print_range(1,7,1,“ ")
>>> Keywords
When calling a function with a number of
parameters with defaults you can modify particular
parameters with a keyword so that you do not need
to specify all preceding parameters.

print_range.py
1 def print_range(start=1,end=1,interval=1,sep=" "):
2 for i in range(start,end,interval):
3 print str(i) + sep,
4 print end
5
6 print range(0,7)
7 print_range(1,7,1,“ ")
8
9 print_range(end=7,sep=“ ")
>>> str1 = "Hello”
>>> str2 = 'there'
>>> bob = str1 +
String Data Type str2
>>> print bob
A string is a sequence of Hellothere
characters >>> str3 = '123'
A string literal uses >>> str3 = str3 + 1
quotes 'Hello' or “Hello” Traceback (most
recent call last):
For strings, + means
File "<stdin>", line
“concatenate” 1, in
When a string contains <module>TypeError:
numbers, it is still a string cannot concatenate
We can convert numbers 'str' and 'int'
objects
in a string into a number >>> x = int(str3) +
using int() 1
>>> print x
raw_input('Enter:')
Enter:Chuck
Reading and >>> print name
Chuck
Converting >>> apple =
• We prefer to read
raw_input('Enter:')
data in using strings Enter:100
and then parse and >>> x = apple – 10
convert the data as Traceback (most
we need recent call last):
• This gives us more File "<stdin>", line
control over error 1, in
situations and/or bad <module>TypeError:
user input unsupported operand
• Raw input numbers type(s) for -: 'str'
must be converted and 'int'
from strings >>> x = int(apple) –
10
>>> print x
Looking Inside Strings

• We can get at any single


character in a string using b a n a n a
an index specified in >>>0 fruit
1 2 3= 4 5
square brackets 'banana'
• The index value must be >>> letter =
fruit[1]
an integer and starts at >>> print letter
zero a
• The index value can be an >>> n = 3
expression that is >>> w = fruit[n -
computed 1]
>>> print w
n
A Character Too Far

• You will get a python


>>> zot = 'abc'
error if you attempt to >>> print zot[5]
index beyond the end of Traceback (most
a string. recent call last):
• So be careful when File "<stdin>",
constructing index line 1, in
<module>IndexError:
values and slices string index out of
range
>>>
Strings Have Length

• There is a built-in function


len that gives us the length
of a string b a n a n a
0 1 2 3 4 5

>>> fruit = 'banana'


>>> print len(fruit)
6
Len Function
A function is
>>> fruit = 'banana' some stored code
>>> x = len(fruit) that we use. A
function takes
>>> print x some input and
6 produces an
output.

'banana'
len() 6
(a string)
functi (a number)

on

Guido wrote this code


Len Function
>>> fruit = 'banana' A function is some
>>> x = len(fruit) stored code that we
use. A function takes
>>> print x some input and
produces an output.
6

def
len(inp):
'banana' blah 6
(a string) blah (a number)
for x in
y:
blah
blah
Looping Through Strings

• Using a while
statement and an
iteration variable,fruit
and = 'banana' 0 b
the len function, index
we = 0
while
can construct a loop index < 1
len(fruit) a:
2 n
to look at each of the letter = fruit[index]
letters in a string 3 a
print index, letter
individually index = index + 1 4 n
5 a
Looping Through Strings

• A definite loop using


a for statement is
b
much more elegant a
n
• The iteration variable
fruit = 'banana' a
is completely taken for letter in fruit
n
:a
care of by the for loop print letter
Looping Through Strings

• A definite loop
fruit = 'banana'
using a for for letter in fruit :
statement is much print letter b
more elegant a
• The iteration
index = 0 n
variable is while index < len(fruit) :
completely taken
a
letter = fruit[index]
care of by the for print letter n
index = index + 1
loop a
Looping and Counting

• This is a simple loop


that loops throughword = 'banana'
each letter in a string
count = 0
and counts the number
of times the loop for letter in word :
encounters the 'a' if letter == 'a'
character.
count = count
print count
Looking deeper into in
 The iteration variable
“iterates” though the
sequence (ordered Six-character string
Iteration variable
set)
 The block (body) of
code is executed
once for each value for letter in 'banana' :
in the sequence print letter
 The iteration variable
moves through all of
the values in the
sequence
Yes
Done Advance b a n a n a
? letter

print
letter

for letter in 'banana'


print letter

The iteration variable “iterates” though the string and


the block (body) of code is executed once for each value
in the sequence
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

 We can also look at


any continuous section >>> s = 'Monty Python
of a string using a >>> print s[0:4]
colon operator Mont
 The second number is >>> print s[6:7]
one beyond the end of P
the slice - “up to but
not including”
>>> print s[6:20]
 If the second number is Python
beyond the end of the
string, it stops at the
end
Slicing Strings
M o n t y P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11

• If we leave off the >>> s = 'Monty Python


first number or the >>> print s[:2]
last number of the Mo
slice, it is assumed to >>> print s[8:]
be the beginning or Thon
end of the string >>> print s[:]
respectively Monty Python

Slicing Strings
String Concatenation
>>> a = 'Hello'
• When the +
>>> b = a + 'There'
operator is>>> print b
applied to HelloThere
strings, it >>> c = a + ' ' + 'Th
means >>> print c
Hello There
"concatenatio
n" >>>
Using in as an Operator
>>> fruit = 'banana’
• The in keyword can >>> 'n' in fruit
also be used to check True
to see if one string is >>> 'm' in fruit
"in" another string False
• The in expression is a >>> 'nan' in fruit
logical expression True
and returns True or >>> if 'a' in fruit :
False and can be used ... print 'Found it!’
in an if statement
...
Found it!
>>>
String Comparison

if word == 'banana':
print 'All right, bananas.'

if word < 'banana':


print 'Your word,' + word + ', comes before banana.’
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.’
else:
print 'All right, bananas.'
String Library
• Python has a number of string
functions which are in the >>> greet = 'Hello
string library Bob‘
• These functions are already >>> zap =
greet.lower()
built into every string - we
>>> print zaphello
invoke them by appending bob
the function to the string >>> print greet
variable Hello Bob
• These functions do not >>> print 'Hi
There'.lower()
modify the original string, hi there
instead they return a new >>>
string that has been altered
>>> type(stuff)<type
'str'>
>>> dir(stuff)
['capitalize', 'center', 'count',
'decode', 'encode', 'endswith',
'expandtabs', 'find', 'format',
'index', 'isalnum', 'isalpha',
'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join',
'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split',
'splitlines', 'startswith',
http://docs.python.org/lib/string-methods.html
'strip', 'swapcase', 'title',
http://docs.python.org/lib/string-methods.html
String Library
r.capitalize() str.replace(old, new[, count])
r.center(width[, fillchar])
str.lower()
r.endswith(suffix[, start[, end]])
str.rstrip([chars])
r.find(sub[, start[, end]])
r.lstrip([chars])
str.strip([chars])
str.upper()

http://docs.python.org/lib/string-methods.html
Searching a
String
• We use the find() b a n a n a
function to search for a
0 1 2 3 4 5
substring within
another string
>>> fruit = 'banana'
• find() finds the first
>>> pos = fruit.find('na
occurance of the >>> print pos
substring 2
• If the substring is not >>> aa = fruit.find('z')
found, find() returns -1 >>> print aa
• Remember that string -1
position starts at zero
Making everything UPPER CASE

• You can make a copy of a


string in lower case or upper >>> greet = 'Hello Bob'
>>> nnn = greet.upper()
case
>>> print nnn
• Often when we are HELLO BOB
searching for a string using >>> www = greet.lower()
>>> print www
find() - we first convert the hello bob
string to lower case so we >>>
can search a string
regardless of case
Search and Replace
>>> greet = 'Hello Bob'
 The replace()
>>> nstr = greet.replace('Bob','Jan
function is>>>
like a print nstr
“search andHello Jane
replace” operation
>>> nstr = greet.replace('o','X')
in a word
>>> print nstrHellX BXb
processor
>>>
 It replaces all
occurrences of the
search string with
the replacement
string
Stripping Whitespace

• Sometimes we want to
>>> greet = ' Hello Bob
take a string and >>> greet.lstrip()
remove whitespace at'Hello Bob '
the beginning and/or >>> greet.rstrip()
end ' Hello Bob'
• lstrip() and rstrip() to >>> greet.strip()
'Hello Bob'
the left and right only>>>
• strip() Removes both
begin and ending
whitespace
Prefixes

>> line = 'Please have a nice day’


>> line.startswith('Please')
rue
>> line.startswith('p')
alse
21 31

From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008

data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14


atpos = data.find('@')
print atpos

sppos = data.find(' ',atpos)


print sppos

host = data[atpos+1 : sppos] Parsing and


Extracting
print host
ac.za
Summary
• String type
• Read/Convert
• Indexing strings []
• Slicing strings [2:4]
• Looping through strings with for and while
• Concatenating strings with +
• String operations
>>> Graphics
Graphics in Python are similar to graphics in Java

• drawingpanel.py needs to be in the same directory


as your program that uses it

• The Graphics (g) in Python behaves like the


Graphics (g) in Java and is passed as a parameter
in the same fashion.

• To let the Python interpreter know that you want


to use the drawingpanel.py file you must add
“from drawingpanel import *” at the top of your
file

• panel.mainloop() must be put at the end of the


program
>>> Graphics Methods
Java Python
g.drawLine(x1, y1, x2, y2); g.create_line(x1, y1, x2, y2)
g.create_line(x1, y1, x2, y2, x3, y3,…, xN, yN)

g.drawOval(x1, y1, width, height); g.create_oval(x1, y1, x2, y2)

g.drawRect(x1, y1, width, height); g.create_rectangle(x1, y1, x2, y2)

panel.setBackground(Color); g[“bg”] = “ <color> “


>>> Graphics Methods

Java
1 DrawingPanel panel = new
2 DrawingPanel(300, 200);
3 Graphics g = panel.getGraphics();
4 panel.setBackground(Color.YELLOW);

Python
1 panel = DrawingPanel(300, 200)
2 g = panel.get_graphics()
3 g["bg"] = "yellow"
4
>>> Graphics
• What about...?
• g.setColor()
• g.fillRect(), g.fillOval()

• Fill colors and borders in Python are set as


parameters in the methods.
Java
1 g.setColor(Color.RED);
2 g.fillRect(x, y, w, h,);
3 g.setColor(Color.BLACK);
4 g.drawRect(x, y, w, h);
Python
1
2 g.create_rectangle(x, y, x+w, y+h,
3 fill=“red”, outline=“black”)
4
>>> Graphics Example 1
Python

1 from drawingpanel import *


2 panel = DrawingPanel(400,380)
3 g = panel.get_graphics()
4 g["bg"]="black“
5 g.create_rectangle(100, 100, 200, 200, fill="red",
6 outline="yellow")
panel.mainloop()
>>> Graphics
• What about...?
• Triangles
• Hexagons
• Etc.

• g.create_polygon(x1, y1, x2, y2,..., xN, yN)

Python
1 from drawingpanel import *
2 panel = DrawingPanel(100,100)
3 g = panel.get_graphics()
4 g.create_polygon(50, 50, 100, 0, 100, 100,
5 fill="green")
panel.mainloop()
>>> Graphics Example 2

Let’s recreate the Java car example in Python:


import java.awt.*;
public class DrawCar {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(200, 100);
panel.setBackground(Color.LIGHT_GRAY);
Graphics g = panel.getGraphics();
g.setColor(Color.BLACK);
g.fillRect(10, 30, 100, 50);
g.setColor(Color.RED);
g.fillOval(20, 70, 20, 20);
g.fillOval(80, 70, 20, 20);
g.setColor(Color.CYAN);
g.fillRect(80, 40, 30, 20);
}
}
>>> Example 2 (auf Python)

Let’s recreate the Java car example in Python:


from drawingpanel import *
panel = DrawingPanel(200,100)
g = panel.get_graphics()
g["bg"] = "gray"
g.create_rectangle(10, 30, 10+100, 30+50, fill="black")
g.create_oval(20, 70, 20+20, 70+20,fill="red“, outline=“red”)
g.create_oval(80, 70, 80+20, 70+20, fill="red“, outline=“red”)
g.create_rectangle(80, 40, 80+30, 40+20, fill="cyan”, outline=“cyan”)
>>> Example 2 - Parameterized

Now, let’s use parameters so that


we can place the cars all over
the DrawingPanel.
>>> Example 2 - Parameterized
from drawingpanel import *
def draw_car(g, x, y):
g.create_rectangle(x, y, x+100, y+50, fill="black")
g.create_oval(x+10, y+40, x+10+20, y+40+20, fill="red", outline="red")
g.create_oval(x+70, y+40, x+70+20, y+40+20, fill="red", outline="red")
g.create_rectangle(x+70, y+10, x+70+30, y+10+20, fill="cyan“, outline=“cy
# main
panel = DrawingPanel(260,100)
g = panel.get_graphics()
g["bg"] = "gray"
draw_car(g, 10, 30)
draw_car(g, 150, 10)
>>> Overview
* if else
* returns
* input
>>> if
Like many things in the Java pytho
transition from Java to
< n
<
Python, curly braces are
replaced with colons and > >
whitespace, the parentheses <= <=
are dropped and &&, || and ! >= >=
change. == ==
Translator.java != !=
1 // 1 for english || or
2 // 2 for german && and
3 int translator = 1; ! not
4 if (translator == 1) {
5 english(); Notice: "else if" becomes
6 } else if (translator == 2) { "elif"
7 german(); translator.py
8 } else { 1 translator = 1
9 System.out.println("None"); 2 if translator == 1:
10 } 3 english()
4 elif translator == 2:
5 german()
else:
print "None"
>>> strings
Just like in Java, strings are objects. Lets look at
different things that we can do with them:

string methods
s = "wow" s.capitalize() => "Wow"
s = "wow" s.endswith("w") => True
s = "wow" s.find("o") => 1
s = "wow" s.islower() => True
s = "wOw" s.isupper() => False
s = "wOw" s.lower() => "wow"
s = "hmmm" s.startswith("hm") => True
s = " ack " s.strip() => "ack"
s = "wOw" s.swapcase() => "WoW"
s = "wow" s.upper() => "WOW"
>>> strings as sequences
Like arrays in Java, sequence operations
strings have zero-based
indexes, and we can s[<index>] s[3] => "c"
access parts of them s[-1] =>
with square brackets "g"
instead of using Java's s[<start>:<end>] s[4:] => "king"
substring() and charAt() s[3:5] =>
methods. "ck"
s[-3:] =>
Lets look at things we "ing"
can do if we have the len(s) len(s) => 8
string Indexing
from the front
0 1 2 3 4 5 6 7
s = "shocking"
"shocking"
from the back
-8 -7 -6 -5 -4 -3 -2 -
example: s[2:-4] => "oc"
>>> return
Returns in python are straightforward. Simply "return <value>"
instead of "return <value>;" and forget about the types.

degrees.py
1 def f_to_c(degreesF):
2 degreesC = 5.0 / 9.0 * (degreesF – 32)
3 return degreesC
4
5 #main
6 temp = f_to_c(68)
7 print ("Temperature is: " + str(temp))

slope.py
1 def slope(x1, y1, x2, y2):
2 return (y2 - y1) / (x2 - x1)
3
4 #main
5 slope = slope(0, 0, 5, 5)
6 print ("Slope is: " + str(slope))
7
>>> math in python
Most of the math functions
are the same in python. Here math functions
is a list with a short
description. ceil(x)
fabs(x)
In order to use them, we floor(x)
have to exp(x)
import math
log(x,[base])
The constants are the same log10(x)
as Java, except lower case. pow(x, y)
sqrt(x)
math.pi = 3.1415926...
cos(x)
math.e = 2.7182818..
hypot(x, y)
sin(x)
Random comes from its own tan(x)
class:
degrees(x)
import random
random.random() radians(x)
>>> input() vs. raw_input()
There are two ways of getting The second way is to use
input. The first is input(). It raw_input() which returns The
takes in input until enter is hit raw_input()` function doesn't
and then tries to interpret it evaluate, it will just read
into python. However, this way whatever you enter.
only
>>> xworks well for ")
= input("yes? numbers.
yes? y
inputs.py
Traceback (most recent call last): 1 name = input("what is your
File "<stdin>", line 1, in 2 name?")
<module> 3 print(name)
File "<string>", line 1, in 4 name = raw_input("what is your
<module> 5 name ?")
NameError: name 'y' is not defined 6
>>> x = input("yes? ") 7
yes? 2 8
>>> print x 9
2 10
>>> x = input("num? ")
num? 2.0
>>> print x
2.0
>>> Overview
* boolean
* while
* random
* tuples
>>> boolean
Just like Java, there are
>>> True
boolean values. These values
True
are True and False.
True >>> False
False
False
>>> 2==3
False
< >>> "this"=="this"
> True
<= >>> 2==3 and 4==4
>= False
== >>> x = not 1 == 2
!= >>> x
or True
and
not
>>> while
The while loop translates sentinel.py
nicely from Java to 1 n = 10
Python. 2 # initialize sum and counter
3 sum = 0
4 i = 1
5 while i <= n:
6 sum = sum + i
7 i = i+1 # update counter
8 # print the sum
9 print("The sum is", sum)

Sentinel.java
1 Scanner console = new Scanner(System.in);
2 int sum = 0;
3 System.out.print("Enter a number (-1 to
4 quit): ");
5 int number = console.nextInt();
6
7 while (number != -1) {
8 sum = sum + number;
9 System.out.print("Enter a number (-1
10 to quit): ");
number = console.nextInt();
}

System.out.println("The total is " +


sum);
>>> random
Just like in Java, python also has random object. Here is
an example:
>>> from random import *
>>> randint(0,9)
1
>>> randint(0,9)
4
>>> choice(range(10))
7

random.randint(a,b)
returns an int between a and b inclusive
random.choice(seq)
returns a random element of the sequence
>>> tuples as points
Python does not have Point Objects. Instead we use tuples.
A tuple is able to hold multiple values. These values can
correspond to the x and y coordinates of a point.

The syntax for a tuple is:

<variable name> = (value1, value 2, ..., valueN)

For a point, we only need two values.

>>> p = (3, 5)
>>> p
(3, 5)
Creates a tuple where the first value is 3 and the second
value is 5. This can represent a 2D point where the “x”
value is 3 and the “y” value is 5.
>>> retrieving tuple values
If we wish to use the values in a
tuple, we can assign each value to a
vairable.
>>> p = (3, 5)
>>> p
(3, 5)

>>> (x, y) = p
>>> x
3
>>> y
5

This creates two new variables x and


y, and assigns the first value in our
tuple to x, and the second value to
y.
>>> parameters and returns
Tuples can be passed just like any other variable.
Once inside a method, we will want to access its
values.

Example:
def equal(p1, p2):
(x1, y1) = p1
(x2, y2) = p2
return x1==x2 and y1==y2

Additionally, we can return tuples. Assume we wanted


to add two two. This does not make much sense for
points, but does for 2D vectors.

def addVectors(p1, p2): NOTE: Tuples are “immutable.”


(x1, y1) = p1 This means that the values
(x2, y2) = p2 within a tuple cannot be
return (x1 + x2, y1 + y2) altered once it has been
created. Because of this, if
we would like to change the
value of our tuples, we must
create a new tuple with the
values we want, and use it
instead.
>>> point distance method
# Calculates the distance between two points
def distance(p1, p2):
(x1, y1) = p1
(x2, y2) = p2
dx = abs(x1 - x2)
dy = abs(y1 - y2)
return sqrt(dx * dx + dy * dy)

You might also like