KEMBAR78
Python - An Introduction | PDF
Python - An Introduction
Eueung Mulyana | http://eueung.github.io/EL6240/py
based on the material @Codecademy
Attribution-ShareAlike CC BY-SA
1 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
2 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
3 / 121
Python Syntax
Basic Types: string, int, float, bool
Function: print(python 2)
Comment: #
print"WelcometoPython!"
my_variable=10
my_int=7
my_float=1.23
my_bool=True
#changevalue
my_int=7
my_int=3
printmy_int
4 / 121
Python Syntax
Note: IndentationError:expectedanindentedblock
#first
defspam():
eggs=12
returneggs
printspam()
#second
defspam():
eggs=12
returneggs
printspam()
5 / 121
Python Syntax
Comment: #, """
Operators: +,-,*,/,**,%
#singlelinecomment
"""test
multilinescomment
"""
addition=72+23
subtraction=108-204
multiplication=108*0.5
division=108/9
#addition
count_to=5000+6000.6
printcount_to
#square,exponentiation,tothepowerof
eggs=10**2
printeggs
#modulo
spam=5%4
printspam
#1,modulo
6 / 121
Python Syntax
Learned:
Variables, which store values for later use
Data types, such as numbers and booleans
Whitespace, which separates statements
Comments, which make your code easier to read
Arithmetic operations, including +, -, , /, *, and %
#comment
monty=True
python=1.234
monty_python=python**2
7 / 121
Python Syntax
Tip Calculator
meal=44.50
#6.75%
tax=0.0675
#15%
tip=0.15
meal=meal+meal*tax
total=meal+meal*tip
print("%.2f"%total)
8 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
9 / 121
Strings and Console Output
Assignment, Escaping Chars
"MONTY"[4]
caesar="Graham"
printcaesar
#Escapingcharacters
abc='Thisisn'tflying,thisisfallingwithstyle!'
printabc
"""
Thestring"PYTHON"hassixcharacters,
numbered0to5,asshownbelow:
+---+---+---+---+---+---+
|P|Y|T|H|O|N|
+---+---+---+---+---+---+
0 1 2 3 4 5
Soifyouwanted"Y",youcouldjusttype
"PYTHON"[1](alwaysstartcountingfrom0!)
"""
fifth_letter="MONTY"[4]
printfifth_letter
#Y
10 / 121
Strings and Console Output
Functions: len(), lower(), upper(), str()
parrot="NorwegianBlue"
printlen(parrot)
#14
#Stringmethods:len(),lower(),upper(),str()
parrot="NorwegianBlue"
printparrot.lower()
printparrot.upper()
#tostring
pi=3.14
printstr(pi)
#review
ministry="TheMinistryofSillyWalks"
printlen(ministry)
printministry.upper()
11 / 121
Strings and Console Output
Printing String Variables
String Concatenation
Functions: raw_input()
#tostring,printingvariables,stringconcatenation
print"Spam"+"and"+"eggs"
print"Thevalueofpiisaround"+3.14
#error
print"Thevalueofpiisaround"+str(3.14)
string_1="Camelot"
string_2="place"
print"Let'snotgoto%s.'Tisasilly%s."%(string_1,string_2)
#stringformatting
name="Mike"
print"Hello%s"%(name)
#stringformatting,tanda%sdan%
#fungsiraw_input(inputdarikeyboardpasruntime)
name=raw_input("Whatisyourname?")
quest=raw_input("Whatisyourquest?")
color=raw_input("Whatisyourfavoritecolor?")
print"Ah,soyournameis%s,yourquestis%s,"
"andyourfavoritecoloris%s."%(name,quest,color)
12 / 121
Strings and Console Output
Date and Time
fromdatetimeimportdatetime
now=datetime.now()
printnow
#member,bukanmethod
printnow.year
printnow.month
printnow.day
print'%s-%s-%s'%(now.year,now.month,now.day)
print'%s/%s/%s'%(now.day,now.month,now.year)
printnow.hour
printnow.minute
printnow.second
print'%s:%s:%s'%(now.hour,now.minute,now.second)
print'%s/%s/%s%s:%s:%s'%(now.day,now.month,now.year,now.hour,now.minute,now.second)
13 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
14 / 121
Conditionals and Control Flow
#raw_input
defclinic():
print"You'vejustenteredtheclinic!"
print"Doyoutakethedoorontheleftortheright?"
answer=raw_input("Typeleftorrightandhit'Enter'.").lower()
ifanswer=="left"oranswer=="l":
print"ThisistheVerbalAbuseRoom,youheapofparrotdroppings!"
elifanswer=="right"oranswer=="r":
print"OfcoursethisistheArgumentRoom,I'vetoldyouthatalready!"
else:
print"Youdidn'tpickleftorright!Tryagain."
clinic()
clinic()
15 / 121
Conditionals and Control Flow
Boolean Comparisons
bool_one=True #17<328
bool_two=True #100==(2*50)
bool_three=True #19<=19
bool_four=False #-22>=-18
bool_five=False #99!=(98+1)
bool_one=False #(20-10)>15
bool_two=False #(10+17)==3**16
bool_three=False#1**2<=-1
bool_four=True #40*4>=-4
bool_five=False #100!=10**2
#-----
bool_one=3<5 #True
bool_two=3>5 #False
bool_three=5==5 #True
bool_four=3!=3 #False
bool_five=3<=3 #True
16 / 121
Conditionals and Control Flow
Operators: and, or
bool_one =FalseandFalse
bool_two =-(-(-(-2)))==-2and4>=16**0.5
bool_three=19%4!=300/10/10andFalse
bool_four =-(1**2)<2**0and10%10<=20-10*2
bool_five =TrueandTrue
#-----
bool_one =2**3==108%100or'Cleese'=='KingArthur'
bool_two =TrueorFalse
bool_three=100**0.5>=50orFalse
bool_four =TrueorTrue
bool_five =1**100==100**1or3*2*1!=3+2+1
17 / 121
Conditionals and Control Flow
Operators: not
bool_one =notTrue
bool_two =not3**4<4**3
bool_three=not10%3<=10%2
bool_four =not3**2+4**2!=5**2
bool_five =notnotFalse
#-----
bool_one =FalseornotTrueandTrue
bool_two =FalseandnotTrueorTrue
bool_three=Trueandnot(FalseorFalse)
bool_four =notnotTrueorFalseandnotTrue
bool_five =Falseornot(TrueandTrue)
#-----
#notfirst,berikutnyaand,or--samaprioritas,klnotnotsamadengannot(not)
bool_one=(2<=2)and"Alpha"=="Bravo"
18 / 121
Conditionals and Control Flow
Conditional Statement
answer="Left"
ifanswer=="Left":
print"ThisistheVerbalAbuseRoom,youheapofparrotdroppings!"
#Willtheaboveprintstatementprinttotheconsole?
#---
defusing_control_once():
ifTrue:
return"Success#1"
defusing_control_again():
ifTrue:
return"Success#2"
printusing_control_once()
printusing_control_again()
19 / 121
Conditionals and Control Flow
Conditional Statement
#condition
answer="'Tisbutascratch!"
defblack_knight():
ifanswer=="'Tisbutascratch!":
returnTrue
else:
returnFalse #MakesurethisreturnsFalse
deffrench_soldier():
ifanswer=="Goaway,orIshalltauntyouasecondtime!":
returnTrue
else:
returnFalse #MakesurethisreturnsFalse
20 / 121
Conditionals and Control Flow
Conditional Statement
#condition
defgreater_less_equal_5(answer):
ifanswer>5:
return1
elifanswer<5:
return-1
else:
return0
printgreater_less_equal_5(4)
printgreater_less_equal_5(5)
printgreater_less_equal_5(6)
#review
defthe_flying_circus():
if5==5: #Startcodinghere!
#Don'tforgettoindent
#thecodeinsidethisblock!
returnTrue
elifTrueandTrue:
#Keepgoinghere.
#You'llwanttoaddtheelsestatement,too!
returnFalse
else:
returnFalse
21 / 121
Conditionals and Control Flow
PygLatin (Python Pig Latin)
Ask the user to input a word in English.
Make sure the user entered a valid word.
Convert the word from English to Pig Latin.
Display the translation result.
print'WelcometothePigLatinTranslator!'
original=raw_input("Enteraword:")
iflen(original)>0andoriginal.isalpha():
printoriginal
else:
print"empty"
22 / 121
Conditionals and Control Flow
PygLatin (Python Pig Latin)
You move the first letter of the word to the end and then append the suffix
'ay'. Example: python->ythonpay
pyg='ay'
original=raw_input('Enteraword:')
iflen(original)>0andoriginal.isalpha():
word=original.lower()
first=word[0]
new_word=word+first+pyg
new_word=new_word[1:len(new_word)]
printnew_word
else:
print'empty'
23 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
24 / 121
Functions
deftax(bill):
"""Adds8%taxtoarestaurantbill."""
bill*=1.08
print"Withtax:%f"%bill
returnbill
deftip(bill):
"""Adds15%tiptoarestaurantbill."""
bill*=1.15
print"Withtip:%f"%bill
returnbill
meal_cost=100
meal_with_tax=tax(meal_cost)
meal_with_tip=tip(meal_with_tax)
25 / 121
Functions
defsquare(n):
squared=n**2
print"%dsquaredis%d."%(n,squared)
returnsquared
square(10)
#---
defpower(base,exponent): #Addyourparametershere!
result=base**exponent
print"%dtothepowerof%dis%d."%(base,exponent,result)
power(37,4) #Addyourargumentshere!
26 / 121
Functions
#Functionscallfunctions
defone_good_turn(n):
returnn+1
defdeserves_another(n):
returnone_good_turn(n)+2
#---
defshout(phrase):
ifphrase==phrase.upper():
return"YOU'RESHOUTING!"
else:
return"Canyouspeakup?"
shout("I'MINTERESTEDINSHOUTING")
#---
defcube(number):
returnnumber**3
defby_three(number):
ifnumber%3==0:
returncube(number)
else:
returnFalse
27 / 121
Functions
Importing a Module: a module is a file that contains definitions—
including variables and functions—that you can use once it is imported
Math Standard Library
#1
importmath
printmath.sqrt(25)
#2
frommathimportsqrt
printsqrt(25)
frommathimport*
printsqrt(25)
#3
importmath
everything=dir(math)#Setseverythingtoalistofthingsfrommath
printeverything #Prints'emall!
"""
['__doc__','__name__','__package__','acos','acosh','asin','asinh','atan','atan2','atanh','ceil','copysign',
"""
28 / 121
Functions
Math
*args: one or more arguments
Functions: max, min, abs
defbiggest_number(*args):
printmax(args)
returnmax(args)
defsmallest_number(*args):
printmin(args)
returnmin(args)
defdistance_from_zero(arg):
printabs(arg)
returnabs(arg)
biggest_number(-10,-5,5,10)
smallest_number(-10,-5,5,10)
distance_from_zero(-10)
#---
maximum=max(2.3,4.1,6)
minimum=min(2.3,4.1,6)
absolute=abs(-42)
printmaximum
29 / 121
Functions
Function: type
printtype(42) #<type'int'>
printtype(4.2) #<type'float'>
printtype('spam') #<type'str'>
#---
defspeak(message):returnmessage
ifhappy():speak("I'mhappy!")
elifsad():speak("I'msad.")
else:speak("Idon'tknowwhatI'mfeeling.")
#---
defshut_down(s):
ifs=="yes":return"Shuttingdown"
elifs=="no":return"Shutdownaborted"
else:return"Sorry"
30 / 121
Functions
defis_numeric(num):
returntype(num)==intortype(num)==float:
#---
defdistance_from_zero(a):
iftype(a)==intortype(a)==float:
returnabs(a)
else:
return"Nope"
31 / 121
Functions
Taking a Vacation
defhotel_cost(nights):return140*nights
defplane_ride_cost(city):
ifcity=="Charlotte":return183
elifcity=="Tampa":return220
elifcity=="Pittsburgh":return222
elifcity=="LosAngeles":return475
defrental_car_cost(days):
costperday=40
ifdays>=7:total=days*costperday-50
elifdays>=3:total=days*costperday-20
else:total=days*costperday
returntotal
deftrip_cost(city,days,spending_money):
returnrental_car_cost(days)+hotel_cost(days)+plane_ride_cost(city)+spending_money
printtrip_cost("LosAngeles",5,600)
32 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
33 / 121
Lists and Dictionaries
List : Array
Dictionary : Asc. Array (notation {} -> object in JS)
List
#list_name=[item_1,item_2],empty[]
zoo_animals=["pangolin","cassowary","sloth","gajah"];
iflen(zoo_animals)>3:
print"Thefirstanimalatthezooisthe"+zoo_animals[0]
print"Thesecondanimalatthezooisthe"+zoo_animals[1]
print"Thethirdanimalatthezooisthe"+zoo_animals[2]
print"Thefourthanimalatthezooisthe"+zoo_animals[3]
34 / 121
Lists and Dictionaries
List
Methods: append, len
suitcase=[]
suitcase.append("sunglasses")
#Yourcodehere!
suitcase.append('a')
suitcase.append('b')
suitcase.append('c')
list_length=len(suitcase)#Setthistothelengthofsuitcase
print"Thereare%ditemsinthesuitcase."%(list_length)
printsuitcase
"""
Thereare4itemsinthesuitcase.
['sunglasses','a','b','c']
"""
35 / 121
Lists and Dictionaries
List
Slicing: [index_inclusive:index_exclusive]
suitcase=["sunglasses","hat","passport","laptop","suit","shoes"]
first =suitcase[0:2] #Thefirstandseconditems(indexzeroandone)
middle=suitcase[2:4] #Thirdandfourthitems(indextwoandthree)
last =suitcase[4:6] #Thelasttwoitems(indexfourandfive)
#<6bukan<=6
#Westartattheindexbeforethecolonandcontinueuptobutnotincludingtheindexafterthecolon.
#---
animals="catdogfrog"
cat =animals[:3] #Thefirstthreecharactersofanimals
dog =animals[3:6] #Thefourththroughsixthcharacters
frog=animals[6:] #Fromtheseventhcharactertotheend
#tanpastart/end
36 / 121
Lists and Dictionaries
List
Methods: index, insert
animals=["aardvark","badger","duck","emu","fennecfox"]
duck_index=animals.index("duck") #Useindex()tofind"duck"
#Yourcodehere!
animals.insert(duck_index,"cobra")
printanimals#Observewhatprintsaftertheinsertoperation
#['aardvark','badger','cobra','duck','emu','fennecfox']
37 / 121
Lists and Dictionaries
List
forelementinthe_list
.sort()
#1
my_list=[1,9,3,8,5,7]
fornumberinmy_list:print2*number
#2
#.sort
start_list=[5,3,1,2,4]
square_list=[]
fornuminstart_list:
square_list.append(num**2)
square_list.sort()
printsquare_list
38 / 121
Lists and Dictionaries
Dict
Key : Value Pair
#dictionarykeyvaluenotasiobject{}
residents={'Puffin':104,'Sloth':105,'BurmesePython':106}
printresidents['Puffin']#PrintsPuffin'sroomnumber
#Yourcodehere!
printresidents['Sloth']
printresidents['BurmesePython']
39 / 121
Lists and Dictionaries
Dict
#---
menu={}#Emptydictionary
menu['ChickenAlfredo']=14.50#Addingnewkey-valuepair
printmenu['ChickenAlfredo']
#append
menu['karedok']=2.2
menu['lotek']=2.3
menu['rujak']=3.3
print"Thereare"+str(len(menu))+"itemsonthemenu."
printmenu
"""
14.5
Thereare4itemsonthemenu.
{'lotek':2.3,'ChickenAlfredo':14.5,'karedok':2.2,'rujak':3.3}
"""
40 / 121
Lists and Dictionaries
Dict
A dictionary (or list) declaration may break across multiple lines
del
#key-animal_name:value-location
zoo_animals={'Unicorn':'CottonCandyHouse',
'Sloth':'RainforestExhibit',
'BengalTiger':'JungleHouse',
'AtlanticPuffin':'ArcticExhibit',
'RockhopperPenguin':'ArcticExhibit'}
#Removingthe'Unicorn'entry.(Unicornsareincrediblyexpensive.)
delzoo_animals['Unicorn']
delzoo_animals['Sloth']
delzoo_animals['BengalTiger']
zoo_animals['RockhopperPenguin']='ArcticExhibitMod'
printzoo_animals
41 / 121
Lists and Dictionaries
List & Dict
remove
Complex Dict
#remove
backpack=['xylophone','dagger','tent','breadloaf']
backpack.remove("dagger")
#---
inventory={
'gold':500,
'pouch':['flint','twine','gemstone'],#Assignedanewlistto'pouch'key
'backpack':['xylophone','dagger','bedroll','breadloaf']
}
#Addingakey'burlapbag'andassigningalisttoit
inventory['burlapbag']=['apple','smallruby','three-toedsloth']
#Sortingthelistfoundunderthekey'pouch'
inventory['pouch'].sort()
inventory['pocket']=['seashell','strangeberry','lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold']+=50
42 / 121
Lists and Dictionaries
A Day at the Supermarket
names=["Adam","Alex","Mariah","Martine","Columbus"]
foriteminnames:printitem
#---
#indentfirstelementdalamdictdalam{},sptdibhslain
webster={
"Aardvark":"Astarofapopularchildren'scartoonshow.",
"Baa":"Thesoundagoatmakes.",
"Carpet":"Goesonthefloor.",
"Dab":"Asmallamount."
}
forkeyinwebster:
printwebster[key]
Note that dictionaries are unordered, meaning that any time you loop
through a dictionary, you will go through every key, but you are not
guaranteed to get them in any particular order.
43 / 121
Lists and Dictionaries
A Day at the Supermarket
a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13]
fornumberina:
ifnumber%2==0:printnumber
#---
defcount_small(numbers):
total=0
forninnumbers:
ifn<10:total=total+1
returntotal
lost=[4,8,15,16,23,42]
small=count_small(lost)
printsmall
#---
deffizz_count(x):
count=0
foriteminx:
ifitem=='fizz':count+=1
returncount
fizz_count(["fizz","cat","fizz"])
44 / 121
Lists and Dictionaries
A Day at the Supermarket
As we've mentioned, strings are like lists with characters as elements. You
can loop through strings the same way you loop through lists!
forletterin"Codecademy":printletter
#Emptylinestomaketheoutputpretty
print
print
word="Programmingisfun!"
forletterinword:
#Onlyprintouttheletteri
ifletter=="i":printletter
45 / 121
Lists and Dictionaries
A Day at the Supermarket
prices={
"banana":4,
"apple":2,
"orange":1.5,
"pear":3
}
stock={
"banana":6,
"apple":0,
"orange":32,
"pear":15
}
forkeyinstock:
printkey
print"price:%s"%prices[key]
print"stock:%s"%stock[key]
46 / 121
Lists and Dictionaries
A Day at the Supermarket
#take2
prices={
"banana":4, "apple" :2,
"orange":1.5,"pear" :3,
}
stock={
"banana":6, "apple" :0,
"orange":32, "pear" :15,
}
forkeyinprices:
printkey
print"price:%s"%prices[key]
print"stock:%s"%stock[key]
total=0
forkeyinprices:
printprices[key]*stock[key]
total+=prices[key]*stock[key]
printtotal
47 / 121
Lists and Dictionaries
A Day at the Supermarket
#take3
shopping_list=["banana","orange","apple"]
stock={
"banana":6, "apple":0,
"orange":32, "pear":15
}
prices={
"banana":4, "apple":2,
"orange":1.5,"pear":3
}
defcompute_bill(food):
total=0
foriteminfood:
ifstock[item]>0:
total+=prices[item]
stock[item]-=1
returntotal
48 / 121
Student Becomes the Teacher
List of Dicts
lloyd={
"name":"Lloyd",
"homework":[90.0,97.0,75.0,92.0],
"quizzes":[88.0,40.0,94.0],
"tests":[75.0,90.0]
}
alice={
"name":"Alice","homework":[100.0,92.0,98.0,100.0],
"quizzes":[82.0,83.0,91.0],"tests":[89.0,97.0]
}
tyler={
"name":"Tyler","homework":[0.0,87.0,75.0,22.0],
"quizzes":[0.0,75.0,78.0],"tests":[100.0,100.0]
}
students=[lloyd,alice,tyler]
forstudentinstudents:
printstudent['name']
printstudent['homework']
printstudent['quizzes']
printstudent['tests']
49 / 121
Student Becomes the Teacher
Arithmetics Notes
5/2
#2
5.0/2
#2.5
float(5)/2
#2.5biarjadifloatkarenaint/int
50 / 121
Student Becomes the Teacher
lloyd={"name":"Lloyd","homework":[90.0,97.0,75.0,92.0],
"quizzes":[88.0,40.0,94.0],"tests":[75.0,90.0]}
alice={"name":"Alice","homework":[100.0,92.0,98.0,100.0],
"quizzes":[82.0,83.0,91.0],"tests":[89.0,97.0]}
tyler={"name":"Tyler","homework":[0.0,87.0,75.0,22.0],
"quizzes":[0.0,75.0,78.0],"tests":[100.0,100.0]}
#---
defaverage(numbers):
total=sum(numbers)
total=float(total)
returntotal/len(numbers)
defget_average(student):
homework=average(student['homework'])
quizzes=average(student['quizzes'])
tests=average(student['tests'])
return0.1*homework+0.3*quizzes+0.6*tests
defget_letter_grade(score):
ifscore>=90:return"A"
elifscore>=80:return"B"
elifscore>=70:return"C"
elifscore>=60:return"D"
else:return"F"
defget_class_average(students):
results=[]
forstudentinstudents:results.append(get_average(student))
returnaverage(results)
51 / 121
Student Becomes the Teacher
average(A-List)returns float
get_average(A-Dict)returns float--> better get_numeric_grade()
get_letter_grade(num)returns string
get_class_average(List-of-Dicts)returns float
#---
students=[lloyd,alice,tyler]
printget_class_average(students)
printget_letter_grade(get_class_average(students))
#---
#classaverage=get_class_average([lloyd,alice,tyler])
#printget_letter_grade(get_average(lloyd))
#---
52 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
53 / 121
Lists and Functions
Access to List
Method: .append(), .pop(), .remove()
Function: del
n=[1,3,5]
#Doyourmultiplicationhere
n[1]*=5
n.append(4)
printn
#[1,15,5,4]
n=[1,3,5]
#Removethefirstiteminthelisthere
n.pop(0)
#ataudel(n[0])
#n.remove(1)value1,bukanindex
#popnge-returnvalue,delvoid
printn
54 / 121
Lists and Functions
#1
n="Hello"
defstring_function(s):
returns+'world'
printstring_function(n)
#2
deflist_function(x):
x[1]+=3
returnx
n=[3,5,7]
printlist_function(n)
#3
n=[3,5,7]
deflist_extender(lst):
lst.append(9);
returnlst
printlist_extender(n)
55 / 121
Lists and Functions
#1range
n=[3,5,7]
defprint_list(x):
foriinrange(0,len(x)):
printx[i]
print_list(n)
#eachline:357
#2
n=[3,5,7]
defdouble_list(x):
foriinrange(0,len(x)):
x[i]=x[i]*2
returnx
printdouble_list(n)
#[6,10,14]
56 / 121
Lists and Functions
#3
range(6)#=>[0,1,2,3,4,5]
range(1,6)#=>[1,2,3,4,5]
range(1,6,3)#=>[1,4]
#range(stop)
#range(start,stop)
#range(start,stop,step)
defmy_function(x):
foriinrange(0,len(x)):
x[i]=x[i]*2
returnx
printmy_function(range(3))#[0,1,2]
#[0,2,4]
57 / 121
Lists and Functions
#1
n=[3,5,7]
deftotal(numbers):
result=0
fornuminnumbers:#foriinrange(len(numbers)):
result+=num #result+=numbers[i]
returnresult
#2
n=["Michael","Lieberman"]
defjoin_strings(words):
result=""
foriteminwords:
result+=item
returnresult
printjoin_strings(n)
58 / 121
Lists and Functions
#3operator+agakbedadipythonbuatlist
m=[1,2,3]
n=[4,5,6]
defjoin_lists(x,y):returnx+y
printjoin_lists(m,n)
#[1,2,3,4,5,6]
#4ListofLists
n=[[1,2,3],[4,5,6,7,8,9]]
defflatten(lists):
results=[]
fornumbersinlists:
fornuminnumbers:results.append(num)
returnresults
printflatten(n)
#[1,2,3,4,5,6,7,8,9]
59 / 121
Lists and Functions
Battleship!
In this project you will build a simplified, one-player version of the classic
board game Battleship! In this version of the game, there will be a single ship
hidden in a random location on a 5x5 grid. The player will have 10 guesses to
try to sink the ship.
#tambahelemenberulangpdlist
board=[]
foriinrange(5):
board.append(["O"]*5)#["O","O","O","O","O"]
printboard#[[],..,[]]
#print1rowelemen,1baris
board=[]
foriinrange(5):
board.append(["O"]*5)#["O","O","O","O","O"]
defprint_board(board):
forrowinboard:printrow
print_board(board)
60 / 121
Lists and Functions
Battleship! (1)
#.joinmethodusesthestringtocombinetheitemsinthelist.
fromrandomimportrandint
board=[]
forxinrange(5):board.append(["O"]*5)
defprint_board(board):
forrowinboard:print"".join(row)
print"Let'splayBattleship!"
print_board(board)
#---
defrandom_row(board):returnrandint(0,len(board)-1)
defrandom_col(board):returnrandint(0,len(board[0])-1)
ship_row=random_row(board)
ship_col=random_col(board)
#printship_row
#printship_col
61 / 121
Lists and Functions
Battleship! (2)
#Multilineifcondition,guess_rownotinrange(5)
forturninrange(4):
print"Turn",turn+1
guess_row=int(raw_input("GuessRow:"))
guess_col=int(raw_input("GuessCol:"))
ifguess_row==ship_rowandguess_col==ship_col:
print"Congratulations!Yousankmybattleship!"
break
else:
if(guess_row<0orguess_row>4)or
(guess_col<0or guess_col>4):
print"Oops,that'snotevenintheocean."
elif(board[guess_row][guess_col]=="X"):
print"Youguessedthatonealready."
else:
print"Youmissedmybattleship!"
board[guess_row][guess_col]="X"
print_board(board)
ifturn==3:
print"GameOver"
62 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
63 / 121
Loops
while
#1
count=0
ifcount<5:
print"Hello,Iamanifstatementandcountis",count
whilecount<=9:
print"Hello,Iamawhileandcountis",count
count+=1
#---
#2
loop_condition=True
whileloop_condition:
print"Iamaloop"
loop_condition=False
#---
#3
num=1
whilenum<=10: #Fillinthecondition
printnum**2
num+=1
64 / 121
Loops
while, break
#---
#4
choice=raw_input('Enjoyingthecourse?(y/n)')
whilechoice!='y'andchoice!='n':
choice=raw_input("Sorry,Ididn'tcatchthat.Enteragain:")
#---
#5break
count=0
whileTrue:
printcount
count+=1
ifcount>=10:
break
#---
65 / 121
Loops
while, else
#6whileelse
importrandom
print"LuckyNumbers!3numberswillbegenerated."
print"Ifoneofthemisa'5',youlose!"
count=0
whilecount<3:
num=random.randint(1,6)
printnum
ifnum==5:
print"Sorry,youlose!"
break
count+=1
else:
print"Youwin!"
#elsedieksekusisetelahkondisifalse;tdkpernahdieksekusisetelahbreak
#---
66 / 121
Loops
while, else
#7
fromrandomimportrandint
#Generatesanumberfrom1through10inclusive
random_number=randint(1,10)
guesses_left=3
whileguesses_left>0:
guess=int(raw_input("Yourguess:"))
ifguess==random_number:
print'Youwin!'
break
guesses_left-=1
else:
print'Youlose.'
67 / 121
Loops
forin
#1
hobbies=[]
#Addyourcodebelow!
foriinrange(3):
hobby=str(raw_input("Yourhobby:"))
hobbies.append(hobby);
#---
#2
thing="spam!"
forcinthing:printc
word="eggs!"
forcinword:printc
68 / 121
Loops
forin
Looping over a Dictionary
#3
phrase="Abirdinthehand..."
forcharinphrase:
ifchar=="A"orchar=="a":
print"X",
else:
printchar,
print
#The,characterafterourprintstatementmeansthat
#ournextprintstatementkeepsprintingonthesameline.
#plus1space
#---
#4Loopingoveradictionary
d={'a':'apple','b':'berry','c':'cherry'}
forkeyind:
printkey+""+d[key]
69 / 121
Loops
forindex,iteminenumerate(list)
fora,binzip(list_a,list_b)
#5
choices=['pizza','pasta','salad','nachos']
print'Yourchoicesare:'
forindex,iteminenumerate(choices):
printindex+1,item
#---
#6
list_a=[3,9,17,15,19]
list_b=[2,4,8,10,30,40,50,60,70,80,90]
fora,binzip(list_a,list_b):
#Addyourcodehere!
ifa>b:
printa
else:
printb
#zipwillcreatepairsofelementswhenpassedtwolists,
#andwillstopattheendoftheshorterlist.
#zipcanhandlethreeormorelistsaswell!
70 / 121
Loops
for, else
#7
fruits=['banana','apple','orange','tomato','pear','grape']
print'Youhave...'
forfinfruits:
iff=='tomato':
print'Atomatoisnotafruit!'#(Itactuallyis.)
break
print'A',f
else:
print'Afineselectionoffruits!'
#sptelsewhile,klbreaktidakdirun,klexitnormalyes
#---
71 / 121
Loops
for, else
#8
fruits=['banana','apple','orange','tomato','pear','grape']
print'Youhave...'
forfinfruits:
iff=='tomato1':#klmatch,executed;elsenever
print'Atomatoisnotafruit!'
break
print'A',f
else:
print'Afineselectionoffruits!'
#---
#9
thelist=['a','b','c']
foriinthelist:
printi
else:
print'completed!'
72 / 121
Loops
Practice Makes Perfect
#1
defis_even(x):
ifx%2==0:returnTrue
else:returnFalse
#---
#2
defis_int(x):
delta=x-int(x)
ifdelta==0.0:returnTrue
else:returnFalse
printis_int(7.0)
printis_int(7.9)
printis_int(-1.2)
73 / 121
Loops
Practice Makes Perfect
#---
#3castkestr,castkeint
defdigit_sum(n):
dsum=0
n_str=str(n)
forcinn_str:dsum+=int(c)
returndsum
printdigit_sum(1234)
#---
#4rekursif
deffactorial(x):
ifx==1:return1
else:returnx*factorial(x-1)
printfactorial(4)
74 / 121
Loops
Practice Makes Perfect
#5
defis_prime(x):
ifx<2:returnFalse
forninrange(x-2):
ifx%(n+2)==0:returnFalse
returnTrue
printis_prime(9)
printis_prime(11)
#---
#6
defreverse(text):
varlength=len(text)
textrev=""
foriinrange(varlength):textrev+=text[varlength-1-i]
returntextrev
printreverse('abc@def')
#Youmaynotusereversedor[::-1]tohelpyouwiththis.
#---
75 / 121
Loops
Practice Makes Perfect
#7
defanti_vowel(text):
rettext=""
forcintext:
clower=c.lower()
ifclower!='a'andclower!='e'andclower!='i'andclower!='o'and
clower!='u':rettext+=c
returnrettext
printanti_vowel("HeyYou!")
#---
score={"a":1,"c":3,"b":3,"e":1,"d":2,"g":2,"f":4,"i":1,"h":4,"k":5,"j":8,"m":3,"l"
defscrabble_score(word):
wordlower=word.lower()
retscore=0
forcinwordlower:
forkeyinscore:
ifkey==c:
retscore+=score[key]
break
returnretscore
printscrabble_score("Helix")
76 / 121
Loops
Practice Makes Perfect
#8
defcensor(text,word):
textlist=text.split()
textlist_new=[]
foritemintextlist:
ifitem!=word:
textlist_new.append(item)
else:
textlist_new.append("*"*len(item))
return"".join(textlist_new)
printcensor("thishackiswackhack","hack")
#---
#9
defcount(sequence,item):
varcount=0
foriinsequence:
ifi==item:varcount+=1
returnvarcount
printcount([1,2,1,1],1)
77 / 121
Loops
Practice Makes Perfect
#10
defpurify(numbers):
retnumbers=[]
fornuminnumbers:
ifnum%2==0:retnumbers.append(num)
returnretnumbers
printpurify([1,2,3])
#---
#11
defproduct(numlist):
res=1
fornuminnumlist:res*=num
returnres
printproduct([4,5,5])
78 / 121
Loops
Practice Makes Perfect
#12
defremove_duplicates(varlist):
newlist=[]
forvarinvarlist:
ifvarnotinnewlist:newlist.append(var)
returnnewlist
printremove_duplicates([1,1,2,2])
#---
#13sorted()
#Themedianisthemiddlenumberinasortedsequenceofnumbers.Ifyouaregivenasequencewith
#anevennumberofelements,youmustaveragethetwoelementssurroundingthemiddle.
#sorted([5,2,3,1,4])-->[1,2,3,4,5]
defmedian(varlist):
sortedlist=sorted(varlist)
length=len(varlist)
iflength%2==1:
returnsortedlist[((length+1)/2-1)]
else:
return(sortedlist[length/2-1]+sortedlist[length/2])/2.0
printmedian([1,1,2]) #1
printmedian([7,3,1,4])#3.5
79 / 121
Exam Statistics
(1)
grades=[100,100,90,40,80,100,85,70,90,65,90,85,50.5]
defprint_grades(grades):
forgradeingrades:printgrade
defgrades_sum(scores):
total=0
forscoreinscores:total+=score
returntotal
defgrades_average(grades):
returngrades_sum(grades)/float(len(grades))
print_grades(grades)
printgrades_sum(grades)
printgrades_average(grades)
80 / 121
Exam Statistics
(2)
defgrades_average(grades):
sum_of_grades=grades_sum(grades)
average=sum_of_grades/float(len(grades))
returnaverage
defgrades_variance(scores):
average=grades_average(scores)
variance=0
forscoreinscores:
variance+=(average-score)**2
variance/=float(len(scores))
returnvariance
defgrades_std_deviation(variance):returnvariance**0.5
variance=grades_variance(grades)
printprint_grades(grades)
printgrades_sum(grades)
printgrades_average(grades)
printgrades_variance(grades)
printgrades_std_deviation(variance)
81 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
82 / 121
Advanced Topics in Python
List Comprehensions
my_dict={
"Name":"Otong",
"Age":23,
"Title":"Dr"
}
printmy_dict.items() #[('Age',23),('Name','Otong'),('Title','Dr')]
printmy_dict.keys() #['Age','Name','Title']
printmy_dict.values()#[23,'Otong','Dr']
forkeyinmy_dict:printkey,my_dict[key]
#Age23
#NameOtong
#TitleDr
#Youshoulduseprinta,bratherthanprinta+""+b
What if we wanted to generate a list according to some logic—for example, a
list of all the even numbers from 0 to 50? List comprehensions are a
powerful way to generate lists using the for/in and if keywords
83 / 121
Advanced Topics in Python
List Comprehensions
#1
evens_to_50=[iforiinrange(51)ifi%2==0]
printevens_to_50
#[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50]
#---------------------------------------------------------
#2
new_list=[xforxinrange(1,6)] #=>[1,2,3,4,5]
doubles=[x*2forxinrange(1,6)] #=>[2,4,6,8,10]
doubles_by_3=[x*2forxinrange(1,6)if(x*2)%3==0]#=>[6]
#---------------------------------------------------------
#3
doubles_by_3=[x*2forxinrange(1,6)if(x*2)%3==0]
even_squares=[x**2forxinrange(1,12)ifx%2==0]
printeven_squares#[4,16,36,64,100]
#---------------------------------------------------------
84 / 121
Advanced Topics in Python
List Comprehensions
#4
c=['C'forxinrange(5)ifx<3]
printc#['C','C','C']
#---------------------------------------------------------
#5
cubes_by_four=[x**3forxinrange(1,11)if(x**3)%4==0]
printcubes_by_four#[8,64,216,512,1000]
#---------------------------------------------------------
#6
l=[i**2foriinrange(1,11)] #Shouldbe[1,4,9,16,25,36,49,64,81,100]
printl[2:9:2]#[9,25,49,81]--2belakang,1diloncat
#listslicing
#[start:end:stride]
#Wherestartdescribeswheretheslicestarts(inclusive),endiswhereitends(exclusive),
#andstridedescribesthespacebetweenitemsintheslicedlist.Forexample,astrideof2
#wouldselecteveryotheritemfromtheoriginallisttoplaceintheslicedlist.
#start&end-->index
85 / 121
Advanced Topics in Python
List Comprehensions
#7
to_five=['A','B','C','D','E']
printto_five[3:] #['D','E']
printto_five[:2] #['A','B']
printto_five[::2]#['A','C','E']
"""
Thedefaultstartingindexis0.
Thedefaultendingindexistheendofthelist.
Thedefaultstrideis1.
"""
#---------------------------------------------------------
#8
my_list=range(1,11)#Listofnumbers1-10
printmy_list[::2]#[1,3,5,7,9]
#---------------------------------------------------------
86 / 121
Advanced Topics in Python
List Comprehensions
#9
letters=['A','B','C','D','E']
printletters[::-1]#['E','D','C','B','A']righttoleft
#---------------------------------------------------------
#10
my_list=range(1,11)
backwards=my_list[::-1]
#---------------------------------------------------------
#11
to_one_hundred=range(101)
backwards_by_tens=to_one_hundred[::-10]
printbackwards_by_tens#[100,90,80,70,60,50,40,30,20,10,0]
#---------------------------------------------------------
#12
to_21=range(1,22)
odds=to_21[::2]
middle_third=to_21[7:14]
87 / 121
Advanced Topics in Python
Lambda - Anonymous Function
Functional programming : means that you're allowed to pass functions around
just as if they were variables or values. The function the lambda creates is an
anonymous function. Lambdas are useful when you need a quick function to
do some work for you.
When we pass the lambda to filter, filter uses the lambda to determine what
to filter, and the second argument (my_list, which is just the numbers 0 – 15) is
the list it does the filtering on.
#ekivalen
lambdax:x%3==0
defby_three(x):returnx%3==0
#---------------------------------------------------------
#filter
my_list=range(16)
printfilter(lambdax:x%3==0,my_list)
#ygbsdibagi3->[0,3,6,9,12,15]
#---------------------------------------------------------
88 / 121
Advanced Topics in Python
Lambda - Anonymous Function
languages=["HTML","JavaScript","Python","Ruby"]
printfilter(lambdax:x=="Python",languages)#['Python']
#---------------------------------------------------------
cubes=[x**3forxinrange(1,11)]
printfilter(lambdax:x%3==0,cubes)
#---------------------------------------------------------
squares=[x**2forxinrange(1,11)]
printfilter(lambdax:x>30andx<=70,squares)#[36,49,64]
#---------------------------------------------------------
89 / 121
Advanced Topics in Python
Recap
#Dictionary
movies={
"MontyPythonandtheHolyGrail":"Great",
"MontyPython'sLifeofBrian":"Good",
"MontyPython'sMeaningofLife":"Okay"
}
printmovies.items()
#forkeyinmovies:printkey,my_dict[key]
#---------------------------------------------------------
#ComprehendingComprehensions
squares=[x**2forxinrange(5)]
threes_and_fives=[xforxinrange(1,16)ifx%3==0orx%5==0]
90 / 121
Advanced Topics in Python
Recap
#ListSlicing
str="ABCDEFGHIJ"
#str[start:end:stride]->start,end,stride=1,6,2
#---------------------------------------------------------
garbled="!XeXgXaXsXsXeXmXXtXeXrXcXeXsXXeXhXtXXmXaXXI"
rev_garbled=garbled[::-1]
message=rev_garbled[::2]
printmessage
#---------------------------------------------------------
#Lambda
my_list=range(16)
printfilter(lambdax:x%3==0,my_list)
garbled="IXXXaXXmXaXXXnXoXXXXXtXhXeXXXXrXsXXXXeXcXXXrXeXtmXXeXsXXXsXaXXXXXXgXeX!XX"
message=filter(lambdax:x!='X',garbled)
printmessage
91 / 121
Advanced Topics in Python
Bitwise Operators
#bitwiseoperator
print5>>4 #RightShift101->0
print5<<1 #LeftShift101->1010
print8&5 #BitwiseAND1000&0101->0
print9|4 #BitwiseOR
print12^42#BitwiseXOR
print~88 #BitwiseNOT
#0|10|0|13|38|-89
#---------------------------------------------------------
#hasiloperasiprint->desimal
print0b1, #1
print0b10, #2
print0b11, #3
print0b100, #4
print0b101, #5
print0b110, #6
print0b111 #7
#1234567
print0b1+0b11 #4
print0b11*0b11#9
92 / 121
Advanced Topics in Python
Bitwise Operators
one=0b1;two=0b10;three=0b11;four=0b100;five=0b101;six=0b110;
seven=0b111;eight=0b1000;nine=0b1001;ten=0b1010;eleven=0b1011;twelve=0b1100
printeight
#---------------------------------------------------------
printbin(1)#0b1
printbin(2)#0b10
printbin(3)#0b11
printbin(4)#0b100
printbin(5)#0b101
#---------------------------------------------------------
printint("1",2) #1
printint("10",2) #2
printint("111",2) #7
printint("0b100",2)#4
printint(bin(5),2) #5
#Printoutthedecimalequivalentofthebinary11001001.
printint("0b11001001",2)#201
#base2semua,pakei0bataugak,sama
93 / 121
Advanced Topics in Python
Bitwise Operators
shift_right=0b1100
shift_left=0b1
shift_right=shift_right>>2
shift_left=shift_left<<2
printbin(shift_right) #0b11
printbin(shift_left) #0b100
#---------------------------------------------------------
printbin(0b1110&0b101)#0b100
printbin(0b1110|0b101)#0b1111
printbin(0b1110^0b101)#xor0b1011
#---------------------------------------------------------
print~1 #-2
print~2 #-3
print~3 #-4
print~42 #-43
print~123#-124
#thisisequivalenttoaddingonetothenumberandthenmakingitnegative.
94 / 121
Advanced Topics in Python
Bitwise Operators
#mask
defcheck_bit4(input):#inputreserved?
mask=0b1000
desired=input&mask
ifdesired>0:return"on"
else:return"off"
#---------------------------------------------------------
a=0b10111011
mask=0b100
printbin(a|mask)#0b10111111
printbin(a^mask)#0b10111111
#---------------------------------------------------------
a=0b11101110
mask=0b11111111 #flip*semua*bita
printbin(a^mask)#0b10001
#---------------------------------------------------------
defflip_bit(number,n):
mask=(0b1<<(n-1))
result=number^mask
returnbin(result)
#xorkalaumask1nge-flip;kalomask0tetap
95 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
96 / 121
Introduction to Classes
Python is an object-oriented programming language, which means it
manipulates programming constructs called objects. You can think of an
object as a single data structure that contains data as well as functions;
functions of objects are called methods.
classFruit(object):
"""Aclassthatmakesvarioustastyfruits."""
def__init__(self,name,color,flavor,poisonous):
self.name=name
self.color=color
self.flavor=flavor
self.poisonous=poisonous
defdescription(self):
print"I'ma%s%sandItaste%s."%(self.color,self.name,self.flavor)
defis_edible(self):
ifnotself.poisonous:print"Yep!I'medible."
else:print"Don'teatme!Iamsuperpoisonous."
#---------------------------------------------------------
lemon=Fruit("lemon","yellow","sour",False)
lemon.description()
lemon.is_edible()
97 / 121
Introduction to Classes
passdoesn't do anything, but it's useful as a placeholder in areas of your
code where Python expects an expression
__init__()function is required for classes, and it's used to initialize the
objects it creates. __init__()always takes at least one argument, self, that
refers to the object being created. You can think of __init__()as the
function that "boots up" each object the class creates.
We can access attributes of our objects using dot notation
classAnimal(object):pass
classAnimal(object):
def__init__(self):pass
classAnimal(object):
def__init__(self,name):self.name=name
zebra=Animal("Jeffrey")
printzebra.name
#---------------------------------------------------------
classSquare(object):
def__init__(self):self.sides=4
my_shape=Square()
printmy_shape.sides
98 / 121
Introduction to Classes
classAnimal(object):
"""Makescuteanimals."""
def__init__(self,name,age,is_hungry):
self.name=name
self.age=age
self.is_hungry=is_hungry
#Notethatselfisonlyusedinthe__init__()function*definition*;
#wedon'tneedtopassittoourinstanceobjects.
zebra=Animal("Jeffrey",2,True)
giraffe=Animal("Bruce",1,False)
panda=Animal("Chad",7,True)
printzebra.name,zebra.age,zebra.is_hungry #Jeffrey2True
printgiraffe.name,giraffe.age,giraffe.is_hungry #Bruce1False
printpanda.name,panda.age,panda.is_hungry #Chad7True
99 / 121
Introduction to Classes
Class Scope
Another important aspect of Python classes is scope. The scope of a variable is
the context in which it's visible to the program.
It may surprise you to learn that not all variables are accessible to all parts of
a Python program at all times. When dealing with classes, you can have
variables that are available everywhere (global variables), variables that are
only available to members of a certain class (member variables), and variables
that are only available to particular instances of a class (instance variables).
100 / 121
Introduction to Classes
Class Scope
variables: global, member, instance
classAnimal(object):
"""Makescuteanimals."""
is_alive=True
def__init__(self,name,age):
self.name=name
self.age=age
zebra=Animal("Jeffrey",2)
giraffe=Animal("Bruce",1)
panda=Animal("Chad",7)
printzebra.name,zebra.age,zebra.is_alive #Jeffrey2True
printgiraffe.name,giraffe.age,giraffe.is_alive #Bruce1True
printpanda.name,panda.age,panda.is_alive #Chad7True
#is_alivemembervariable;name,ageinstancevariables
101 / 121
Introduction to Classes
Class Scope
classAnimal(object):
is_alive=True
def__init__(self,name,age):
self.name=name
self.age=age
defdescription(self):
printself.name
printself.age
hippo=Animal("Nil",5)
hippo.description()
#---------------------------------------------------------
hippo=Animal("Jake",12)
cat=Animal("Boots",3)
printhippo.is_alive #True
hippo.is_alive=False
printhippo.is_alive #False
printcat.is_alive #True
102 / 121
Introduction to Classes
Class Scope
classAnimal(object):
is_alive=True
health="good"
def__init__(self,name,age):
self.name=name
self.age=age
defdescription(self):
printself.name
printself.age
hippo=Animal("Nil",5)
hippo.description()
sloth=Animal("slothName",6)
ocelot=Animal("ocelotName",7)
printhippo.health #good
printsloth.health #good
printocelot.health#good
#membervariable=classvariable(bukaninstance,availabletoallinst)
103 / 121
Introduction to Classes
Class Scope
classShoppingCart(object):
"""Createsshoppingcartobjects
forusersofourfinewebsite."""
items_in_cart={}
def__init__(self,customer_name):
self.customer_name=customer_name
defadd_item(self,product,price):
"""Addproducttothecart."""
ifnotproductinself.items_in_cart:
self.items_in_cart[product]=price
printproduct+"added."
else:
printproduct+"isalreadyinthecart."
defremove_item(self,product):
"""Removeproductfromthecart."""
ifproductinself.items_in_cart:
delself.items_in_cart[product]
printproduct+"removed."
else:
printproduct+"isnotinthecart."
104 / 121
Introduction to Classes
Class Scope
my_cart1=ShoppingCart("Otong")
my_cart2=ShoppingCart("Udjang")
my_cart1.add_item("Obeng",2000) #Obengadded.
my_cart1.add_item("Obeng",1000) #Obengisalreadyinthecart.
printmy_cart1.items_in_cart #{'Obeng':2000}
my_cart2.add_item("Sapu",2000) #Sapuadded.
my_cart2.add_item("Sapu",1000) #Sapuisalreadyinthecart.
printmy_cart2.items_in_cart #{'Obeng':2000,'Sapu':2000}
my_cart1.add_item("Sapu",5000) #Sapuisalreadyinthecart.
printmy_cart1.items_in_cart #{'Obeng':2000,'Sapu':2000}
my_cart2.items_in_cart={'Buku':3000}
printmy_cart2.items_in_cart #{'Buku':3000}
printmy_cart1.items_in_cart #{'Obeng':2000,'Sapu':2000}
my_cart2.add_item("Sapu",1000) #Sapuadded.
printmy_cart2.items_in_cart #{'Sapu':1000,'Buku':3000}
my_cart1.add_item("Dodol",10000)#Dodoladded.
printmy_cart1.items_in_cart #{'Obeng':2000,'Sapu':2000,'Dodol':10000}
printmy_cart2.items_in_cart #{'Sapu':1000,'Buku':3000}
105 / 121
Introduction to Classes
Classes can be very useful for storing complicated objects with their own
methods and variables. Defining a class is much like defining a function, but
we use the class keyword instead.
We also use the word object in parentheses because we want our classes to
inherit the object class. This means that our class has all the properties of an
object, which is the simplest, most basic class. Later we'll see that classes can
inherit other, more complicated classes.
Notes for Variables:
To create instance variables, initialize them in the init function
When Python sees self.X (object.X) it looks if there's a property X in your
object, and if there is none, it looks at its class.
106 / 121
Introduction to Classes
Inheritance
Inheritance is the process by which one class takes on the attributes and
methods of another, and it's used to express an is-a relationship.
For example, a Panda is a bear, so a Panda class could inherit from a Bear
class.
classCustomer(object):
"""Producesobjectsthatrepresentcustomers."""
def__init__(self,customer_id):
self.customer_id=customer_id
defdisplay_cart(self):
print"I'mastringthatstandsinforthecontentsofyourshoppingcart!"
classReturningCustomer(Customer):
"""Forcustomersoftherepeatvariety."""
defdisplay_order_history(self):
print"I'mastringthatstandsinforyourorderhistory!"
monty_python=ReturningCustomer("ID:12345")
monty_python.display_cart() #Customer.display_cart
monty_python.display_order_history() #ReturningCustomer
107 / 121
Introduction to Classes
Inheritance
classShape(object):
"""Makesshapes!"""
def__init__(self,number_of_sides):
self.number_of_sides=number_of_sides
classTriangle(Shape):
def__init__(self,side1,side2,side3):
self.side1=side1
self.side2=side2
self.side3=side3
#Override__init__
segitiga2=Triangle(1,2,3)
printsegitiga2.side1
#printsegitiga2.number_of_sides#super?
108 / 121
Introduction to Classes
Inheritance
classEmployee(object):
def__init__(self,name):
self.name=name
defgreet(self,other):
print"Hello,%s"%other.name
classCEO(Employee):
defgreet(self,other):
print"Getbacktowork,%s!"%other.name
ceo=CEO("Emily")
emp=Employee("Steve")
emp.greet(ceo)#Hello,Emily
ceo.greet(emp)#Getbacktowork,Steve!
109 / 121
Introduction to Classes
Inheritance
Sometimes you'll want one class that inherits from another to not only
take on the methods and attributes of its parent, but to override one or
more of them.
On the flip side, sometimes you'll be working with a derived class (or
subclass) and realize that you've overwritten a method or attribute
defined in that class' base class (also called a parent or superclass) that
you actually need. Have no fear! You can directly access the attributes or
methods of a superclass with Python's built-in super call.
110 / 121
Introduction to Classes
Inheritance
classEmployee(object):
"""Modelsreal-lifeemployees!"""
def__init__(self,employee_name):
self.employee_name=employee_name
defcalculate_wage(self,hours):
self.hours=hours
returnhours*20.00
classPartTimeEmployee(Employee):
defcalculate_wage(self,hours):
self.hours=hours
returnhours*12.00
deffull_time_wage(self,hours):
returnsuper(PartTimeEmployee,self).calculate_wage(hours)
milton=PartTimeEmployee("Milton")
printmilton.full_time_wage(10)
111 / 121
Introduction to Classes
classTriangle(object):
number_of_sides=3
def__init__(self,angle1,angle2,angle3):
self.angle1=angle1
self.angle2=angle2
self.angle3=angle3
defcheck_angles(self):
sum_angle=self.angle1+self.angle2+self.angle3
ifsum_angle==180:returnTrue
else:returnFalse
classEquilateral(Triangle):
angle=60
def__init__(self):
self.angle1=self.angle
self.angle2=self.angle
self.angle3=self.angle
my_triangle=Triangle(90,30,60)
printmy_triangle.number_of_sides#3inherited
printmy_triangle.check_angles() #True
112 / 121
Introduction to Classes
classCar(object):
condition="new"
def__init__(self,model,color,mpg):
self.model=model;self.color=color;self.mpg=mpg
defdisplay_car(self):
return"Thisisa%s%swith%sMPG."%(self.color,self.model,str(self.mpg))
defdrive_car(self):self.condition="used"
classElectricCar(Car):
def__init__(self,model,color,mpg,battery_type):
super(ElectricCar,self).__init__(model,color,mpg)
self.battery_type=battery_type
defdrive_car(self):self.condition="likenew"
my_car=ElectricCar("DeLorean","silver",88,"moltensalt")
printmy_car.condition#new
my_car.drive_car() #
printmy_car.condition#likenew
my_car1=Car("DeLorean","silver",88)
printmy_car1.condition #new
printmy_car1.model #DeLorean
printmy_car1.display_car() #ThisisasilverDeLoreanwith88MPG.
my_car1.drive_car()
printmy_car1.condition #used
113 / 121
Introduction to Classes
Usually, classes are most useful for holding and accessing abstract
collections of data.
One useful class method to override is the built-in __repr__()method,
which is short for representation; by providing a return value in this
method, we can tell Python how to represent an object of our class (for
instance, when using a print statement).
classPoint3D(object):
def__init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
def__repr__(self):
return"(%d,%d,%d)"%(self.x,self.y,self.z)
my_point=Point3D(1,2,3)
printmy_point#(1,2,3)
114 / 121
Agenda
1. Python Syntax
2. Strings and Console Output
3. Conditionals and Control Flow
4. Functions
5. Lists and Dictionaries
6. Lists and Functions
7. Loops
8. Advanced Topics in Python
9. Introduction to Classes
10. File Input and Output
115 / 121
File Input and Output
Built-in io functions
Write
#Generatesalistofsquaresofthenumbers1-10
my_list=[i**2foriinrange(1,11)]
f=open("output.txt","w")
foriteminmy_list:f.write(str(item)+"n")
f.close()
#ThistoldPythontoopenoutput.txtin"w"mode("w"standsfor"write").
#Westoredtheresultofthisoperationinafileobject,f.
116 / 121
File Input and Output
Write
my_list=[i**2foriinrange(1,11)]
my_file=open("output.txt","r+")
foriinmy_list:my_file.write(str(i)+"n")
my_file.close()
#"r+"asasecondargumenttothefunctionsothe
#filewillallowyoutoreadandwrite
117 / 121
File Input and Output
Read
my_file=open("output.txt","r")
printmy_file.read()
my_file.close()
#---
#ifwewanttoreadfromafilelinebyline,
#ratherthanpullingtheentirefileinatonce.
my_file=open("text.txt","r")
printmy_file.readline()
printmy_file.readline()
printmy_file.readline()
my_file.close()
118 / 121
File Input and Output
During the I/O process, data is buffered: this means that it is held in a
temporary location before being written to the file.
Python doesn't flush the buffer—that is, write data to the file—until it's
sure you're done writing. One way to do this is to close the file. If you
write to a file without closing, the data won't make it to the target file.
#Openthefileforreading
read_file=open("text.txt","r")
#Useasecondfilehandlertoopenthefileforwriting
write_file=open("text.txt","w")
#Writetothefile
write_file.write("NotclosingfilesisVERYBAD.")
write_file.close()
#Trytoreadfromthefile
printread_file.read()
read_file.close()
119 / 121
File Input and Output
File objects contain a special pair of built-in methods: __enter__()and
__exit__(). The details aren't important, but what is important is that
when a file object's __exit__()method is invoked, it automatically closes
the file. How do we invoke this method? With with and as.
withopen("text.txt","w")astextfile:
textfile.write("Success!")
#gakperluclose,closeautomatically
#---------------------------------------------------------
f=open("bg.txt")
f.closed #False
f.close()
f.closed #True
#---------------------------------------------------------
withopen("text.txt","w")asmy_file:
my_file.write("otong");
ifmy_file.closed==False:my_file.close()
printmy_file.closed
120 / 121
Python - An Introduction
END
Eueung Mulyana | http://eueung.github.io/EL6240/py
based on the material @Codecademy
Attribution-ShareAlike CC BY-SA
121 / 121

Python - An Introduction