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

Lecture 13 Python

Python lecture

Uploaded by

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

Lecture 13 Python

Python lecture

Uploaded by

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

CSEg 1101 Introduction to Computing

Lecture 13

Fall 2023/24

Computer science and Engineering


The School of EE & Computing
Adama Science & Technology University
OUTLINES ASTU

Dictionaries (Chapter 10 of the textbook)


Named parameters
Files (Chapter 11 of the textbook)
Formatting
String methods

Reading assignment:
Chapter 13 of the textbook (Classes and functions)
Sections 14.1~14.5 in Chapter 14 of the textbook
(Classes and methods)

12/19/2024 2
DICTIONARIES ASTU

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 dictionary consists of a key and a value.
The key is a value of any immutable type and
used as an index of the item.

12/19/2024 3
ASTU

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

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

>>>medals[1]
KeyError: 1

12/19/2024 4
ASTU

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)

{'one': 1, 'two': 2, 'three': 3, 'four': 4,


'five': 5}

12/19/2024 5
ASTU

Search and change


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

12/19/2024 6
ASTU

Add and remove


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

12/19/2024 7
ASTU

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

one 1
two 2
three 3
four 4
five 5

12/19/2024 8
ASTU

Converting to a list

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


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

12/19/2024 9
ASTU

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

12/19/2024 10
ASTU

stg = “maintain”
count = {}
for c in stg:
if c not in count:
count[c] = 1
else:
count[c] += 1
print (count)

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

12/19/2024 11
ASTU

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


want to use the 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 not in inverse:
inverse[frequency] = [c]
else:
inverse[frequency].append(c)
print (inverse)
12/19/2024 12
NAMED PAREMETERS ASTU

In general, there is a positional correspondence


between parameters and arguments: Arguments are
mapped to 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”)

12/19/2024 13
ASTU

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 !

12/19/2024 14
ASTU

By using the names of parameters in a function call,


the 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!

12/19/2024 15
FILES ASTU

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

12/19/2024 16
ASTU

Reading from a file


>>> f = open("cseg1101/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)

12/19/2024 17
ASTU

Reading the entire file with a single statement

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


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

We obtain a list with white space appearing again!

12/19/2024 18
ASTU

Reading the entire file line by line


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

Mercury Venus Earth Mars Jupiter Saturn Uranus


Neptune

You may also use rstrip. Why?


12/19/2024 19
ASTU

Finding the line containing “Earth”

f = open(“cseg1101/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) + “.”)

12/19/2024 20
ASTU

Appending a line

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


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

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

12/19/2024 21
FORMATTING ASTU

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
How ?
James Brown 10000
James Brown 10000

12/19/2024 22
ASTU

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
12/19/2024 23
ASTU

x1 = input(“x1 = “) “60”
x2 = 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

12/19/2024 24
ASTU

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
12/19/2024 25
ASTU

8.3f: 8 indicates total


Field width: length
>>>”%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 shopping.'
>>>“%-20s spent % -10d for shopping.” % (name,
amount)
'Joseph S. Shin spent 100000 for shopping.‘
>>>”My name is %-15s .” % name
“My name is Joseph S. Shin .”

12/19/2024 26
STRING METHODS ASTU

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

12/19/2024 27
ASTU

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.

12/19/2024 28
ASTU

>>> "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'

12/19/2024 29
ASTU

String methods for converting between list and string


split() to split with white space as separators
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', 'much.']
>>>lt = ['I', 'like', 'this', 'course', 'very',
'much.']
>>>” “.join(lt)
‘I like this course very much.’

12/19/2024 30

You might also like