Lecture15 Python - Basics, Strings and Lists
Lecture15 Python - Basics, Strings and Lists
Lecture15 Python - Basics, Strings and Lists
the Basics
PRINTING
Some Python codes
• 6+9
• Print 6+9
• Print “6+9”
• aa=6+9
print aa
• aa=6 bb=9
aa+bb
Print
• Python command print – Displays data, values, and expressions
• The single and double quotation mark string objects, which are
collections of texts surrounded by quotes.
Be familiar with Python printing
>>> "hello"
'hello'
>>> "world"
'world'
>>> "hello"+"world"
'helloworld'
Be familiar with Python printing
>>> "hello" * 3
'hellohellohello'
• Examples: x = 5
gpa = 3.14
x 5 gpa 3.14
• A variable that has been given a value can be used in expressions.
x + 4 is 9
8
Everything is an object
• Everything means
>>> x = 7
everything, including >>> x
functions and classes 7
(more on this later!) >>> x = 'hello'
>>> x
'hello'
>>>
• Data type is a property
of the object and not of
the variable
Look
Look at a of
at a sample sample
code… of code…
assignments, arithmetics, if, print
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
Declare a variable and assign its
value Example: Area of a rectangle
>>> width = 20
>>> height = 45
>>> area
900
Evaluation of expressions in Python
>>> 10 + 25
35
>>> 1/3
0.333333333333333
Print of long lines
• print : Produces text output on the console.
• Syntax:
print "Message"
print Expression
• Prints the given text message or expression value on the console, and moves the cursor
down to the next line.
print Item1, Item2, ..., ItemN
• Prints several messages and/or expressions on the same line.
• Example:
print "Hello, world!"
age = 45
print "You have", 65 - age, "years until retirement"
Output:
Hello, world!
You have 20 years until retirement
13
Enough to Understand the Code
• Assignment uses = and comparison uses ==.
• Floats
x = 3.456
• Strings
Can use “ ” or ‘ ’ to specify. “abc” ‘abc’ (Same thing.)
thing
Unmatched ones can occur within the string. “matt’s”
Use triple double-quotes for multi-line strings or strings than
contain both ‘ and “ inside of them: “““a‘b“c”””
Comments
• Start comments with # – the rest of line is ignored.
>>> a=3
>>> b=4
>>> a+1
>>> b*3
>>> b/3
>>> b/3.0
>>> b**2
>>> 2+4.0
>>> 2.0**b
Hello World
Program
Hello World Program
main()
{
printf("hello, world\n");
}
“Hello World” in C
#include <iostream>
using namespace std;
main()
{
cout<<“Hello World” ;
}
“Hello World” in JAVA
class myfirstjavaprog
{
public static void main(String args[])
{
System.out.println("Hello World!");
}
}
“Hello World” in Python
28
Integer division
• When we divide integers with / , the quotient is also an integer.
3 52
4 ) 14 27 ) 1425
12 135
2 75
54
21
• More examples:
• 35 / 5 is 7
• 84 / 10 is 8
• 156 / 100 is 1
29
Real numbers
• When integers and reals are mixed, the result is a real number.
• Example: 1 / 2.0 is 0.5
• The conversion occurs on a per-operator basis.
• 7 / 3 * 1.2 + 3 / 2
• 2 * 1.2 + 3 / 2
• 2.4 + 3 / 2
• 2.4 + 1
• 3.4
30
Math commands
• Python has useful commands for performing calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
• To use many of these commands, you must write the following at the top of your Python program:
from math import * 31
Numbers
Number in Action
>>> 1 / 2.0
0.5
>>> 1/2
0
>>> 1 % 2
1
Simple Data Types
End of lecture 1
Numbers are immutable
x 4.5
>>> x = 4.5
>>> y=x y
>>> y += 3
>>> x 4.5
x
4.5
>>> y y 7.5
7.5
Strings
Strings
• The next major build-in type is the Python STRING ---
an ordered collection of characters to store and
represent text-based information
1. len() length
2. + concatenate
3. * repetition
len()
• The len build-in function returns the length of strings
>>> a=‘abc’
>>> len(a)
+
• Adding two string objects creates a new string
object
>>> a=‘Hello’
>>> b=‘World’ Hello World with
>>> a + b space
>>> a+ ‘ ’ +b
Concatenation of strings
*
• Repetition may seem a bit obscure at first,
but it comes in handy in a surprising number
of contexts
index 0 1 2 3 4 5 6 7
character P . D i d d y
50
More examples on Index
and slice
>>> aa=“SLICEOFSPAM”
>>> aa[0], aa[-2]
(‘S’,’A’)
>>> aa[1:3], aa[1:], aa[:-1]
(‘LI’, ‘LICEOFSPAM’, ‘SLICEOFSPA’)
String Methods: modifying and checking strings
assigned to variables
• Assign a string to a variable
• In this case “hw”
• hw.title()
• hw.upper()
• hw.isdigit()
• hw.islower()
• The string held in your variable
remains the same
• The method returns an altered string
• Changing the variable requires
reassignment
• hw = hw.upper()
• hw now equals “HELLO WORLD”
Substrings and Methods
• len(String) – returns the
>>> s = '012345' number of characters in the
>>> s[3] String
'3'
>>> s[1:4] • str(Object) – returns a String
'123' representation of the Object
>>> s[2:]
'2345'
>>> s[:4]
'0123'
>>> s[-2] >>> len(x)
'4' 6
>>> str(10.3)
'10.3'
String Literals: immutable and
overloading
Example
String Literals: Many Kinds
• Can use single or double quotes, and three double quotes
for a multi-line string
• A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
57
Examples of Strings
• "hello"+"world" "helloworld" # concatenation
• "hello"*3 "hellohellohello" # repetition
• "hello"[0] "h" # indexing
• "hello"[-1] "o" # (from end)
• "hello"[1:4] "ell" # slicing
• len("hello") 5 # size
• "hello" < "jello" 1 # comparison
• "e" in "hello" 1 # search
• New line: "escapes: \n "
• Line continuation: triple quotes ’’’
• Quotes: ‘single quotes’, "raw strings"
Text and File
Processing
59
Using len, str.lower and str.upper on STRINGS
• Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
60
raw_input: reading text from
input
Task
Create a cryptographic systems for your
63
two robots to communicate
File processing
• Many programs handle data, which often comes from files.
Example:
file_text = open("bankaccount.txt").read()
64
Line-by-line processing
• Reading a file line-by-line:
for line in open("filename").readlines():
End of
statements
lecture 2
Example: counting the number of lines in the file
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print "The file contains", count, "lines."
PROBLEM
Recall the Genetic Algorithm. Write a Python code for GA.
Encode robot’s characteristics in chromosomes.
We have done such examples in class.
We will use this method for our robots. 65
Containers
Python Objects: Lists, Tuples,
Dictionaries
• Lists (mutable sets of strings)
• var = [] # create list
• var = [‘one’, 2, ‘three’, ‘banana’]
• Tuples (immutable sets)
• var = (‘one’, 2, ‘three’, ‘banana’)
• Dictionaries (associative arrays or ‘hashes’)
• var = {} # create dictionary
• var = {‘lat’: 40.20547, ‘lon’: -74.76322}
• var[‘lat’] = 40.2054
Similarities
Similar Syntax of tuples and lists
• Tuples and lists are sequential containers that share
much of the same syntax and functionality.
• For conciseness, they will be introduced together.
• The operations shown in this section can be applied to both
tuples and lists,
• but most examples will just show the operation performed on one
or the other.
1 -2 -1
0 2 or -3
Positive index:
index count from the left, starting with 0.
>>> t[1]
‘abc’
Negative lookup:
lookup count from right, starting with –1.
>>> t[-3]
4.56
Slicing: Return Copy of a Subset, part 1
Value of variable t is a tuple:
a lre a dy f or strings
this
We illustrated
Copying the Whole Container
>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)
>>> p = “cat”
>>> j = [‘cat’, ‘dog’]
>>> p in j
True
>>> ‘a’ in p
True
>>> ‘t’ in p[:2]
False
cat
Range function
• Python has a range function to easily form lists
of integers.
>>> range(5)
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
>>> range(2,5)
[2, 3, 4] [0, 1, 2, 3, 4]
The + Operator
>>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’)
• Lists are defined using square brackets (and commas).
>>> li = [“abc”, 34, 4.34, 23]
• Strings are defined using quotes (“, ‘, or “““).
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> “Hello” * 3
‘HelloHelloHello’
Lists
Lists are the most flexible containers
A B
• Accessed by offset
--- you can fetch a component object out of a list by
indexing the list on the object’s offset
--- you can also use lists for such tasks as slicing and
concatenation
Declaring Lists
pointer
Pointer to NIL
A B
>>> aa*3
List in action: len and in
• Lists also have the function len() to tell the size of lists and “in”
function
>>> aa=[1,2,3]
>>> len(aa) # test of len
>>> 3 in aa # test of in
Append
List method calls
The list append method simply tacks a
single item onto the end of the list
>>> aa=[]
Pay attention to this
syntax with a dot >>> aa.append(1) [1]
1 2 3 ‘4’ 5.0
Lists = STACK OF CARDS METAPHOR
how to think about them
• Think of a list as a stack of cards,
cards on which your information is written
• The information stays in the order you place it in until you modify that
order
• Methods:
• return a string or subset of the list
• or modify the list to add or remove components
• del a[-1] # -> [98, "bottles", "of", "beer"] Last element removed
More list operations: range, append, pop, insert,
reverse, sort
>>> t[1][1]
2 Second element from second
element
Lists: Modifying Content
• x[i] = a reassigns the
ith element to the >>> x = [1,2,3]
value a >>> y = x
>>> x[1] = 15
• Since x and y point to >>> x
the same list object, [1, 15, 3]
>>> y
both are changed [1, 15, 3]
• The method append
x
also modifies the list
y
1 2 3
15
Lists: Modifying Content
• x[i] = a reassigns the >>> x = [1,2,3]
ith element to the >>> y = x
>>> x[1] = 15
value a >>> x
[1, 15, 3]
• Since x and y point to >>> y
the same list object, [1, 15, 3]
both are changed >>> x.append(12)
>>> y
• The method append [1, 15, 3, 12]
x
also modifies the list
y
1 15 3
12
Lists: Modifying Contents >>> x = [1,2,3]
>>> y = x
>>> z = x.append(12)
• The method append >>> z == None
modifies the list and True
>>> y
returns None [1, 2, 3, 12]
>>> x = x + [9,10]
• List addition (+) >>> x
[1, 2, 3, 12, 9, 10]
returns a new list >>> y
[1, 2, 3, 12]
y >>>
1 15 3 12
1 15 3 12 10
Lists in ArcToolbox
>>> li.append(‘a’)
>>> li
[1, 2, 3, 4, 5, ‘a’]
>>> li
[1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [9, 8, 7]]
More operations on Lists Only
>>> li = [5, 2, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Tuples vs. Lists,
conversions
• Lists are slower but more powerful than tuples.
• Lists can be modified, and they have lots of handy
operations we can perform on them.
• Tuples are immutable and have fewer features.
d = { "foo" : 1, "bar" : 2 }
print d["bar"] # 2
some_dict = {}
some_dict["foo"] = "yow!"
print some_dict.keys() # ["foo"]
Dictionary details
adds
Dictionaries: Deleting Elements
>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
The whole
pair is
removed
Copying Dictionaries and Lists
f = file("foo", "r")
We read a line
line = f.readline()
from file object f
print line,
ct
f.close()
ob j e
file
e th
i s # Can use sys.stdin as input;
clo s
We # Can use sys.stdout as output.
Files: Input
input = open(‘data’, ‘r’) Open the file for input
print "Hi %s! You are %d years old!" % (name, 2011 - birthyear)
~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 31 years old!
Booleans
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0 respectively
Boolean Expressions
In file ifstatement.py
Indentation and
Blocks
• Python uses whitespace and indents to denote blocks of code
• Lines within the code block are indented at the same level
• You'll want blocks of code that run only when certain conditions
are met
Conditional
Branching Ends with a colon
• if and else
if variable == condition:
identation #do something based on v == c
else:
#do something based on v != c
• elif allows for additional branching
Ends with a colon
if condition:
Ends with a colon
elif another condition:
…
else: #none of the above
While Loops
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
7
8
In whileloop.py 9
>>>
In interpreter
Looping
with
For
Looping with For
• For allows you to loop over a block of code a set
number of times