0% found this document useful (0 votes)
71 views30 pages

Spring 2015: Programming

The document outlines a lecture on dictionaries, named parameters, files, formatting strings, and string methods in Python, providing examples of how to create and manipulate dictionaries, use default and named parameters in functions, read from and write to files, format output strings, and utilize common string methods. It also assigns reading from the textbook on dictionaries, named parameters, and files.

Uploaded by

ola
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views30 pages

Spring 2015: Programming

The document outlines a lecture on dictionaries, named parameters, files, formatting strings, and string methods in Python, providing examples of how to create and manipulate dictionaries, use default and named parameters in functions, read from and write to files, format output strings, and utilize common string methods. It also assigns reading from the textbook on dictionaries, named parameters, and files.

Uploaded by

ola
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

CCE20003 HGU

CCE20003 PROGRAMMING I
Lecture 13

Spring 2015

ICT Convergence Division


School of Creative Convergence Education
Handong Global University
OUTLINES CCE20003 HGU

Dictionaries
Named parameters
Files
Formatting
String methods

Reading assignment:
Chapter 13 of the textbook
Sections 14.1~14.5 in Chapter 14 of the textbook
DICTIONARIES CCE20003 HGU

Given the name of a country(key), how can we know the


medal information of this country(value)?

Use a dictionary!

A dictionary is a collection of items( or elements). It is


an object of type dict. Every item(or element) of a dictio
nary consists of a key and a value. The key is a value of
any immutable type and used as an index of the item.
CCE20003 HGU

medals = {}
medals = {“United States”: (46, 29, 29), “China”:
(38, 27, 23), “Great Britain”:(29, 17, 19), ... ,
“Australia”: (7, 16, 12)}

>>>medals[“United States”]
(46, 29, 29)
>>>medals[“Rep. of Korea”]
(13, 8, 7)

>>>medals[1]
KeyError: 1
CCE20003 HGU

Creating a dictionary
txt = (“one”, “two”, “three”, “four”, “five”)
num = (1, 2, 3, 4, 5)
dict1 = {}
for i in range(len(txt)):
dict1[txt[i]] = num[i]
print dict1

{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'o


ne': 1}
CCE20003 HGU

Search and change


>>>dict1 = {“four”:4, “three”:3, “five”: 5, ”two”:2,
“one”:1}
>>>dict1[“three”]
3
>>>dict1[“five”]
5
>>>dict1[“one”] = “nice”
>>>dict1
{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one': ‘nice’}
>>>dict1[“one”] = 1
>>>dict1
{'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one': 1}
CCE20003 HGU

Add and remove


>>>dict1[“nine”] = 9
>>>dict1
{'three': 3, 'one': 1, 'four': 4, 'nine': 9, 'five':
5}
>>>dict1.pop[“nine”]
>>>dict1
{'three': 3, 'one': 1, 'four': 4, 'five': 5}
CCE20003 HGU

Traversing a dictionary
>>>dict1={'four': 4, 'three': 3, 'five': 5, 'two': 2, 'one':
1}
>>>for key in dict1:
print key, dict1[key]

four 4
one 1
five 5
three 3
two 2
CCE20003 HGU

Converting to a list

>>>dict1 = {“four”: 4, “three”: 3, “five”: 5, “two”: 2, “one”: 1}


>>>lst = dict1.items()
>>>lst
[('four', 4), ('one', 1), ('five', 5), ('three', 3), ('two', 2)]
CCE20003 HGU

Case study

Given a string, count the number of every character that


appears in it, using a dictionary.

stg = “maintain”

m a i n t
1 2 2 2 1
CCE20003 HGU

stg = “maintain”
count = {}
For c in stg:
if c in count:
count[c] += 1
else:
count[c] = 1
print count

{'a': 2, 'i': 2, 'm': 1, 't': 1, 'n': 2}


CCE20003 HGU

Now we are to invert the dictionary. In other words, we want to use th


e frequencies as keys.:
{ 1: [“m”. “t”], 2: [a”, “i”, “n”]}

count = {'a': 2, 'i': 2, 'm': 1, 't': 1, 'n': 2}


inverse = {}
for c in count:
frequency = count[c]
if frequency in inverse:
inverse[frequency].append(c)
else:
inverse[frequency] = [c]
print inverse

{1: ['m', 't'], 2: ['a', 'i', 'n']}


NAMED PAREMETERS CCE20003 HGU

In general, there is a positional correspondence betwee


n parameters and arguments: Arguments are mapped t
o parameters one-by-one and left-to-right.

def create_sun(radius, color):


sun = Circle(radius)
sun.setFillColor(color)
radius 30
sun.setBorderColor(color) color “yellow”
sun.moveTo(100, 100)
return sun
create_sun(30, “yellow”)
CCE20003 HGU

Default parameters
def create_sun(radius = 30, color = “yellow”):
sun = Circle(radius)
sun.setFillColor(color)
sun.setBorderColor(color)
sun.moveTo(100, 100)
return sun
sun = create_sun()
star = create_sun(2) OK !
moon = create_sun(28, “red”)
moon =create_sun(“red”) Wrong !
CCE20003 HGU

By using the names of parameters in a function call, th


e order of arguments does not matter.

moon = create_sun(color = “red”)


moon = create_sun(color = “red”, radius = 28)

moon = create_sun(color = “red”, 28) Wrong!


FILES CCE20003 HGU

Creating a file
f = open("cce20003/planets.txt", “w")
for i in range(8): Mercury
planet = raw_input (“Enter a planet”) Venus
f.write(planet + “\n”) Earth
Mars
f.close() Jupiter
Saturn
f.writelines((“Mercury\n”, “Venus\n”, … , Uranus
“Neptune”)) Neptune
CCE20003 HGU

Reading from a file


>>> f = open("cce20003/planets.txt", "r")
>>> s = f.readline()
f is an object
>>> s, len(s)
of type file!
('Mercury\n', 8)

line separator
How to get rid of white space?
>>>s.strip(), len(s.strip())
(‘Mercury’, 7)
CCE20003 HGU

Reading the entire file with a single statement

>>>f = open("cce20003/planets.txt", "r")


>>>f.readlines()
['Venus\n', 'Earth\n', 'Mars\n', 'Jupiter\n', 'S
aturn\n', ‘Uranus\n', 'Neptune\n']

We obtain a list with white space appearing again!


CCE20003 HGU

Reading the entire file line by line


f = open("cce20003/planets.txt", "r")
for line in f: for-loop with the file object f calls
s = line.strip() readline() automatically at each
iteration and stops after reading
print s, the last line of the file.
f.close()

Mercury Venus Earth Mars Jupiter Uranus Neptune

You may also use rstrip. Why?


CCE20003 HGU

Finding the line containing “Earth”

f = open(“cce20003/planets.txt”, “r”)
count = 0
in_file = False Apply lower() to
for line in f: line.strip().
count += 1
if line.strip().lower() == “earth”
in_file = True
break Get out of the loop.
if in_file:
print “Earth is in line”, str(count) + “.”
CCE20003 HGU

Appending a line

>>>f = open(“cce20003/planets.txt”, “a”)


>>>f.write(“ Pluto\n”)

What if we use “w” instead of “a” ?


FORMATTING CCE20003 HGU

Format string

lst = [(“Smith Young”, 1000), (“S. Joseph”, 100000),


( “Y. Kim”, 500), (“James Brown, 10000”)]
for name, money in lst:
print name, money

Smith Young 1000 Smith Young 1000


S. Joseph 100000 S. Joseph 100000
Y. Kim 500 Y. Kim 500
James Brown 10000 James Brown 10000
CCE20003 HGU

Smith Young 1000


S. Joseph 100000
Y. Kim 500
James Brown 10000
11 2 6

………………………
for name, money in lst:
print “%-11s %6d” % (name, money)
2 spaces
left-aligned
CCE20003 HGU

x1 = raw_input(“x1 = “) “60”
x2 = raw_input(“x2 = “) “150”
val = int(x1) + int(x2) 210
print str(val) + “ is “ + x1 + “ + “ + x2
210 is 60 + 150
val x1 x2
print “%d is %s + %s”% (val, x1, x2)

place holders
CCE20003 HGU

Format operators
format string % (arg0, arg1, …..)
Every element in the tuple has its corresponding place
holder in the format string.

Place holders
%d integers in decimal
%s strings
%g floats
%f floats

%.5g # of significant digits is 5


%.5f # of digit after the decimal point
CCE20003 HGU

Field width:
>>>”%8.3f %8.3g” % ( 123.456789, 123.456789)
' 123.457 123'
>>>name = “Joseph S. Shin”
>>>amount = 100000
>>>“%20s spent % 10d for shopping.” % (name, amount)
' Joseph S. Shin spent 100000 for shoppi
ng.'
>>>“%-20s spent % -10d for shopping.” % (name, amoun
t)
'Joseph S. Shin spent 100000 for shopp
ing.‘
>>>”My name is %-15s .” % name
STRING METHODS CCE20003 HGU

A string is an immutable sequence of characters.

in operator
>>>”abc” in “01234abcdefg”
True
>>>”fgh” in “01234abceefg”
False
A bit different from the
usage for tuples & lists
CCE20003 HGU

String objects have many useful methods:

- upper(), lower(), and capitalize()


- isalpha() and isdigit()
- startswith(prefix) and endswith(suffix)
- find(str), find(str, start), and find(str, start, end)
(return -1 if str is not in the string )
- replace(str1, str2)
- rstrip(), lstrip() and strip() to remove
white space on the right, left, or both ends.
CCE20003 HGU

>>> "joseph is My name".capitalize()


'Joseph is my name‘
>>>”12345”.isdigit()
True
>>>”This book is mine”.startswith(”this”)
False
>>>”This book is mine”.find(“book”)
5
>>>”This book is mine. That is also mine”.replace(“mine”, “yours”)
'This book is yours. That is also yours'
CCE20003 HGU

String methods for converting between list and string


split() to split with white space as separator
split(sep) to split with a given separator sep
join(lt) to create a string by concatenating its
elements
>>> "I like\rthis\ncourse\tvery much.".split()
['I', 'like', 'this', 'course', 'very', 'muc
h.']
>>>lt = ['I', 'like', 'this', 'course', 'very',
'much.']
>>>” “.join(lt)
‘I like this course very much.’

You might also like