Professional Documents
Culture Documents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
PythonProgramming
#importisusedtomakespecialtyfunctionsavailable
#Thesearecalledmodules
importrandom
importsys
importos
#Helloworldisjustonelineofcode
#print()outputsdatatothescreen
print("HelloWorld")
'''
Thisisamultilinecomment
'''
#Avariableisaplacetostorevalues
#Itsnameislikealabelforthatvalue
name="Derek"
print(name)
#Avariablenamecancontainletters,numbers,or_
#butcan'tstartwithanumber
#Thereare5datatypesNumbers,Strings,List,Tuple,Dictionary
#Youcanstoreanyoftheminthesamevariable
name=15
print(name)
#Thearithmeticoperators+,,*,/,%,**,//
#**Exponentialcalculation
#//FloorDivision
print("5+2=",5+2)
print("52=",52)
print("5*2=",5*2)
print("5/2=",5/2)
print("5%2=",5%2)
print("5**2=",5**2)
print("5//2=",5//2)
#OrderofOperationstates*and/isperformedbefore+and
print("1+23*2=",1+23*2)
print("(1+23)*2=",(1+23)*2)
#Astringisastringofcharacterssurroundedby"or'
#Ifyoumustusea"or'betweenthesamequoteescapeitwith\
quote="\"Alwaysrememberyourunique,"
#Amultilinequote
multi_line_quote='''just
likeeveryoneelse"'''
print(quote+multi_line_quote)
#Toembedastringinoutputuse%s
print("%s%s%s"%('Ilikethequote',quote,multi_line_quote))
#Tokeepfromprintingnewlinesuseend=""
print("Idon'tlike",end="")
print("newlines")
#Youcanprintastringmultipletimeswith*
print('\n'*5)
http://www.newthinktank.com/2014/11/pythonprogramming/
1/8
7/26/2016
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
PythonProgramming
#LISTS
#Alistallowsyoutocreatealistofvaluesandmanipulatethem
#Eachvaluehasanindexwiththefirstonestartingat0
grocery_list=['Juice','Tomatoes','Potatoes','Bananas']
print('Thefirstitemis',grocery_list[1])
#Youcanchangethevaluestoredinalistbox
grocery_list[0]="GreenJuice"
print(grocery_list)
#Youcangetasubsetofthelistwith[min:uptobutnotincludingmax]
print(grocery_list[1:3])
#Youcanputanydatatypeinaalistincludingalist
other_events=['WashCar','PickupKids','CashCheck']
to_do_list=[other_events,grocery_list]
print(to_do_list)
#Gettheseconditeminthesecondlist(Boxesinsideofboxes)
print(to_do_list[1][1])
#Youaddvaluesusingappend
grocery_list.append('onions')
print(to_do_list)
#Insertitematgivenindex
grocery_list.insert(1,"Pickle")
#Removeitemfromlist
grocery_list.remove("Pickle")
#Sortsitemsinlist
grocery_list.sort()
#Reversesortitemsinlist
grocery_list.reverse()
#deldeletesanitematspecifiedindex
delgrocery_list[4]
print(to_do_list)
#Wecancombinelistswitha+
to_do_list=other_events+grocery_list
print(to_do_list)
#Getlengthoflist
print(len(to_do_list))
#Getthemaxiteminlist
print(max(to_do_list))
#Gettheminimumiteminlist
print(min(to_do_list))
#TUPLES
#Valuesinatuplecan'tchangelikelists
pi_tuple=(3,1,4,1,5,9)
#Converttupleintoalist
new_tuple=list(pi_tuple)
http://www.newthinktank.com/2014/11/pythonprogramming/
2/8
7/26/2016
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
PythonProgramming
#Convertalistintoatuple
#new_list=tuple(grocery_list)
#tuplesalsohavelen(tuple),min(tuple)andmax(tuple)
#DICTIONARYorMAP
#Madeupofvalueswithauniquekeyforeachvalue
#Similartolists,butyoucan'tjoindictswitha+
super_villains={'Fiddler':'IsaacBowin',
'CaptainCold':'LeonardSnart',
'WeatherWizard':'MarkMardon',
'MirrorMaster':'SamScudder',
'PiedPiper':'ThomasPeterson'}
print(super_villains['CaptainCold'])
#Deleteanentry
delsuper_villains['Fiddler']
print(super_villains)
#Replaceavalue
super_villains['PiedPiper']='HartleyRathaway'
#Printthenumberofitemsinthedictionary
print(len(super_villains))
#Getthevalueforthepassedkey
print(super_villains.get("PiedPiper"))
#Getalistofdictionarykeys
print(super_villains.keys())
#Getalistofdictionaryvalues
print(super_villains.values())
#CONDITIONALS
#Theif,elseandelifstatementsareusedtoperformdifferent
#actionsbasedoffofconditions
#ComparisonOperators:==,!=,>,<,>=,<=
#Theifstatementwillexecutecodeifaconditionismet
#WhitespaceisusedtogroupblocksofcodeinPython
#Usethesamenumberofproceedingspacesforblocksofcode
age=30
ifage>16:
print('Youareoldenoughtodrive')
#Useanifstatementifyouwanttoexecutedifferentcoderegardless
#ofwhethertheconditionwsmetornot
ifage>16:
print('Youareoldenoughtodrive')
else:
print('Youarenotoldenoughtodrive')
#Ifyouwanttocheckformultipleconditionsuseelif
#Ifthefirstmatchesitwon'tcheckotherconditionsthatfollow
ifage>=21:
print('Youareoldenoughtodriveatractortrailer')
elifage>=16:
print('Youareoldenoughtodriveacar')
else:
http://www.newthinktank.com/2014/11/pythonprogramming/
3/8
7/26/2016
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
PythonProgramming
print('Youarenotoldenoughtodrive')
#Youcancombineconditionswithlogicaloperators
#LogicalOperators:and,or,not
if((age>=1)and(age<=18)):
print("Yougetabirthdayparty")
elif(age==21)or(age>=65):
print("Yougetabirthdayparty")
elifnot(age==30):
print("Youdon'tgetabirthdayparty")
else:
print("Yougetabirthdaypartyyeah")
#FORLOOPS
#Allowsyoutoperformanactionasetnumberoftimes
#Rangeperformstheaction10times09
forxinrange(0,10):
print(x,'',end="")
print('\n')
#Youcanuseforloopstocyclethroughalist
grocery_list=['Juice','Tomatoes','Potatoes','Bananas']
foryingrocery_list:
print(y)
#Youcanalsodefinealistofnumberstocyclethrough
forxin[2,4,6,8,10]:
print(x)
#Youcandoubleupforloopstocyclethroughlists
num_list=[[1,2,3],[10,20,30],[100,200,300]]
forxinrange(0,3):
foryinrange(0,3):
print(num_list[x][y])
#WHILELOOPS
#Whileloopsareusedwhenyoudon'tknowaheadoftimehowmany
#timesyou'llhavetoloop
random_num=random.randrange(0,100)
while(random_num!=15):
print(random_num)
random_num=random.randrange(0,100)
#Aniteratorforawhileloopisdefinedbeforetheloop
i=0
while(i<=20):
if(i%2==0):
print(i)
elif(i==9):
#Forcesthelooptoendalltogether
break
else:
#Shorthandfori=i+1
i+=1
#Skipstothenextiterationoftheloop
continue
i+=1
#FUNCTIONS
http://www.newthinktank.com/2014/11/pythonprogramming/
4/8
7/26/2016
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
PythonProgramming
#Functionsallowyoutoreuseandwritereadablecode
#Typedef(define),functionnameandparametersitreceives
#returnisusedtoreturnsomethingtothecallerofthefunction
defaddNumbers(fNum,sNum):
sumNum=fNum+sNum
returnsumNum
print(addNumbers(1,4))
#Can'tgetthevalueofrNumbecauseitwascreatedinafunction
#Itissaidtobeoutofscope
#print(sumNum)
#Ifyoudefineavariableoutsideofthefunctionitworkseveryplace
newNum=0
defsubNumbers(fNum,sNum):
newNum=fNumsNum
returnnewNum
print(subNumbers(1,4))
#USERINPUT
print('Whatisyourname?')
#StoreseverythingtypedupuntilENTER
name=sys.stdin.readline()
print('Hello',name)
#STRINGS
#Astringisaseriesofcharacterssurroundedby'or"
long_string="I'llcatchyouifyoufallTheFloor"
#Retrievethefirst4characters
print(long_string[0:4])
#Getthelast5characters
print(long_string[5:])
#Everythinguptothelast5characters
print(long_string[:5])
#Concatenatepartofastringtoanother
print(long_string[:4]+"bethere")
#Stringformatting
print("%cismy%sletterandmynumber%dnumberis%.5f"%('X','favorite',
#Capitalizesthefirstletter
print(long_string.capitalize())
#Returnstheindexofthestartofthestring
#casesensitive
print(long_string.find("Floor"))
#Returnstrueifallcharactersareletters'isn'taletter
print(long_string.isalpha())
#Returnstrueifallcharactersarenumbers
print(long_string.isalnum())
#Returnsthestringlength
print(len(long_string))
#Replacethefirstwordwiththesecond(Addanumbertoreplacemore)
http://www.newthinktank.com/2014/11/pythonprogramming/
5/8
7/26/2016
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
PythonProgramming
print(long_string.replace("Floor","Ground"))
#Removewhitespacefromfrontandend
print(long_string.strip())
#Splitastringintoalistbasedonthedelimiteryouprovide
quote_list=long_string.split("")
print(quote_list)
#FILEI/O
#Overwriteorcreateafileforwriting
test_file=open("test.txt","wb")
#Getthefilemodeused
print(test_file.mode)
#Getthefilesname
print(test_file.name)
#Writetexttoafilewithanewline
test_file.write(bytes("Writemetothefile\n",'UTF8'))
#Closethefile
test_file.close()
#Opensafileforreadingandwriting
test_file=open("test.txt","r+")
#Readtextfromthefile
text_in_file=test_file.read()
print(text_in_file)
#Deletethefile
os.remove("test.txt")
#CLASSESANDOBJECTS
#TheconceptofOOPallowsustomodelrealworldthingsusingcode
#Everyobjecthasattributes(color,height,weight)whichareobjectvariables
#Everyobjecthasabilities(walk,talk,eat)whichareobjectfunctions
classAnimal:
#Nonesignifiesthelackofavalue
#Youcanmakeavariableprivatebystartingitwith__
__name=None
__height=None
__weight=None
__sound=None
#Theconstructoriscalledtosetuporinitializeanobject
#selfallowsanobjecttorefertoitselfinsideoftheclass
def__init__(self,name,height,weight,sound):
self.__name=name
self.__height=height
self.__weight=weight
self.__sound=sound
defset_name(self,name):
self.__name=name
defset_height(self,height):
self.__height=height
defset_weight(self,height):
http://www.newthinktank.com/2014/11/pythonprogramming/
6/8
7/26/2016
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
PythonProgramming
self.__height=height
defset_sound(self,sound):
self.__sound=sound
defget_name(self):
returnself.__name
defget_height(self):
returnstr(self.__height)
defget_weight(self):
returnstr(self.__weight)
defget_sound(self):
returnself.__sound
defget_type(self):
print("Animal")
deftoString(self):
return"{}is{}cmtalland{}kilogramsandsays{}".format(self.__name
#HowtocreateaAnimalobject
cat=Animal('Whiskers',33,10,'Meow')
print(cat.toString())
#Youcan'taccessthisvaluedirectlybecauseitisprivate
#print(cat.__name)
#INHERITANCE
#Youcaninheritallofthevariablesandmethodsfromanotherclass
classDog(Animal):
__owner=None
def__init__(self,name,height,weight,sound,owner):
self.__owner=owner
self.__animal_type=None
#Howtocallthesuperclassconstructor
super(Dog,self).__init__(name,height,weight,sound)
defset_owner(self,owner):
self.__owner=owner
defget_owner(self):
returnself.__owner
defget_type(self):
print("Dog")
#Wecanoverwritefunctionsinthesuperclass
deftoString(self):
return"{}is{}cmtalland{}kilogramsandsays{}.Hisowneris{}"
#Youdon'thavetorequireattributestobesent
#Thisallowsformethodoverloading
defmultiple_sounds(self,how_many=None):
ifhow_manyisNone:
print(self.get_sound)
else:
print(self.get_sound()*how_many)
http://www.newthinktank.com/2014/11/pythonprogramming/
7/8
7/26/2016
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
PythonProgramming
spot=Dog("Spot",53,27,"Ruff","Derek")
print(spot.toString())
#Polymorphismallowsusetorefertoobjectsastheirsuperclass
#andthecorrectfunctionsarecalledautomatically
classAnimalTesting:
defget_type(self,animal):
animal.get_type()
test_animals=AnimalTesting()
test_animals.get_type(cat)
test_animals.get_type(spot)
spot.multiple_sounds(4)
http://www.newthinktank.com/2014/11/pythonprogramming/
8/8