Download presentation
Presentation is loading. Please wait.
Published byNelson Hodges Modified over 8 years ago
1
CHAPTER 14. PYTHON SUNG-DONG KIM DEPT. OF COMPUTER ENGINEERING, HANSUNG UNIVERSITY
2
ABSTRACT Introduction Running Python Data types & operators Number String List Tuple Set Dictionaries (2013-1) Understanding of Programming Languages 2
3
ABSTRACT Flow control if while for break, continue Function File I/O Exception handling Module Class (2013-1) Understanding of Programming Languages 3
4
INTRODUCTION (1) Interpreter language Object oriented language Script language Easy to learn High portability (2013-1) Understanding of Programming Languages 4
5
INTRODUCTION (2) Features No variable declaration, but definition before use No default value for all variables initialization String, list, set, tuple: variable size Unicode Indentation Web program, mobile app development Python interpreter on web browser (2013-1) Understanding of Programming Languages 5
6
1. RUNNING PERL Python interpreter installation http://www.python.org Execution on internet explorer shell.appspot.com Execution on google chrome “Python Shell” from web store (2013-1) Understanding of Programming Languages 6
7
2. DATA TYPES (1): NUMBER Number +, -, *, /, % (2013-1) Understanding of Programming Languages 7 >>> 18 / 4 4.5 >>> 18 // 4 4
8
2. DATA TYPES (2): STRING String ‘’, “” (2013-1) Understanding of Programming Languages 8 >>> “Tom\’s book”# 1 Tom’s book >>> “Tom’s book”# 2 Tom’s book >>> ‘Tom’s book’ SyntaxError: invalid syntax >>>’Tom\’s book’# 3 “Tom’s book” >>> ‘”Yes,” he said’# 4 ‘”Yes,” he said’ >>> “’Yes,’ he said”# 5 “’Yes,’ he said”
9
2. DATA TYPES (3): STRING Operators + * (2013-1) Understanding of Programming Languages 9 >>> word1 = ‘Python’ + ‘ ‘+ ‘Language’ >>> word1 ‘Python Language’ >>> word2 = ‘Python’ ‘Programming’ “Language” >>> word2 ‘PythonProgrammingLanguage’ >>> word1*2 ‘Python LanguagePython Language’
10
2. DATA TYPES (4): STRING String slicing = make substring (2013-1) Understanding of Programming Languages 10 >>> word2[0] ‘P’ >>> word2[0:6] ‘Python’ >>> str = word2[:3]# str = word[0:3] >>> str ‘Pyt’ >>> word2[3:]# word2[3:len(word2)] ‘honProgrammingLanguage’
11
2. DATA TYPES (5): LIST List Similar to Perl’s array Same operators for string (2013-1) Understanding of Programming Languages 11 >>> list1 = [“Python”, “Perl”, 13, 12] >>> list2 = [10, 11, “C”, “C++”] >>> list1 + list2# 연결 (concatenation) [‘Python’, ‘Perl’, 13, 12, 10, 11, ‘C’, ‘C++’] >>> list1 * 2# 반복 (repetition) >>> list1[0] ‘Python’ >>> list1[:2]# list1[0:2] [‘Python’, ‘Perl’] >>> list1[-1]# list1[len(list1)-1] 12 >>> list2[1:-1] [11, ‘C’]
12
2. DATA TYPES (6): LIST Insertion, deletion List slicing (2013-1) Understanding of Programming Languages 12 >>> list[idx : idx] = [v1, v2] # idx 위치에 v1, v2 를 삽입 >>> list[from: to] =[] # from 부터 to-1 까지를 삭제 >>> list1[1:1] = ['Perl'] >>> list1 ['Python', 'Perl', 'C', 13, 12] >>> list1[3:3] = ['Pascal', 3] # list1[3] 의 위치에 2 개의 값을 삽입 >>> list1 ['Python', 'Perl', 'C', 'Pascal', 3, 13, 12] >>> list1[2:3] = [] # list1[2] 의 요소를 삭제 >>> list1 ['Python', 'Perl', 'Pascal', 3, 13, 12] >>> list1[3:5] = [] # list1[3] ~ list1[4] 의 요소를 삭제 >>> list1 ['Python', 'Perl', 'Pascal', 12]
13
2. DATA TYPES (7): LIST insert(), append(), extend(), pop(), remove() methods (2013-1) Understanding of Programming Languages 13 >>> list1 = ['Python', 'Perl', 'C', 'C++'] >>> list1.insert(0, 'Ruby')# 리스트 앞에 ‘Ruby’ 삽입 >>> list1 ['Ruby', 'Python', 'Perl', 'C', 'C++'] >>> list1.extend(["C#", 'Java'])# 리스트 뒤에 “C#”, “Java” 삽입 >>> list1 ['Ruby', 'Python', 'Perl', 'C', 'C++', 'C#', 'Java'] >>> list1.append(len(list1))# 리스트 뒤에 리스트의 길이 추가 >>> list1 ['Ruby', 'Python', 'Perl', 'C', 'C++', 'C#', 'Java', 7]
14
(2013-1) Understanding of Programming Languages 14 >>> list1.pop()# 리스트 뒤의 요소를 제거하고 반환 7 >>> list1 ['Ruby', 'Python', 'Perl', 'C', 'C++', 'C#', 'Java'] >>> list1.pop(5)# list[5] 원소를 제거하고 반환 'C#' >>> list1 ['Ruby', 'Python', 'Perl', 'C', 'C++', 'Java'] >>> list1.remove("C")# 리스트에서 “C” 원소를 제거 >>> list1 ['Ruby', 'Python', 'Perl', 'C++', 'Java']
15
2. DATA TYPES (8): LIST Functions for list handling: index(), count(), sort(), reverse() (2013-1) Understanding of Programming Languages 15 >>> list1.index(‘Python’)# list1 에서 ‘Python’ 의 인덱스를 반환 1 >>> list1.count(‘Perl’)# list1 에서 ‘Perl’ 의 개수를 반환 1 >>> list1.sort()# list1 의 요소를 정렬 >>> list1 ['C++', 'Java', 'Perl', 'Python', 'Ruby'] >>> list1.reverse()# list1 의 요소를 역순으로 재배열 >>> list1 ['Ruby', 'Python', 'Perl', 'Java', 'C++']
16
2. DATA TYPES (9): TUPLE Tuple Comma 로 분리되는 여러 개의 값 (2013-1) Understanding of Programming Languages 16 >>> aT = 1, 2, 'Phtyon', ['a', 'b', 2]# 1 >>> aT (1, 2, 'Phtyon', ['a', 'b', 2]) >>> aT[2]# 2 'Phtyon' >>> aT[2] = ‘C#’# tuple element change: X TypeError: 'tuple' object does not support item assignment >>> aT[3][0] = 'A'# list element change: O >>> aT (1, 2, 'Phtyon', ['A', 'b', 2]) >>> bT = aT, "Perl", 'C++', 'C'# nested tuple >>> bT ((1, 2, 'Phtyon', ['a', 'b', 2]), 'Perl', 'C++', 'C')
17
2. DATA TYPES (10): TUPLE Operators: +, * (2013-1) Understanding of Programming Languages 17 >>> aT = 1, 2 >>> bT 'a' >>> bT = 'a', 'b' >>> aT + bT# 튜플의 연결 (1, 2, 'a', 'b') >>> aT * 2# 튜플의 반복 (1, 2, 1, 2) >>> aT.count(1)# count() 메소드 1 >>> bT.index('b')# index() 메소드 1
18
2. DATA TYPES (11): SET Set (2013-1) Understanding of Programming Languages 18 >>> aS = {'a', 'b', 1, 2 } >>> aS {1, 2, 'b', 'a'} >>> bS = {1, 2, 1} >>> bS {1, 2} >>> bS[0] … TypeError: 'set' object does not support indexing >>> cS = set('Korea Team') >>> cS {'r', 'T', ' ', 'a', 'e', 'K', 'm', 'o'}# 1
19
2. DATA TYPES (12): SET Set operators: union, intersection, difference (2013-1) Understanding of Programming Languages 19 >>> aS | bS# aS 와 bS 의 합집합 {1, 2, 'a', 'b'} >>> aS & bS# aS 와 bS 의 교집합 {1, 2} >>> aS – bS# aS 와 bS 의 차집합 {'a', 'b'} >>> aS ^ bS# aS | bS – aS & bS {'a', 'b'} >>> 1 in aS True >>> 3 not in aS True
20
2. DATA TYPES (13): DICTIONARIES Dictionaries Similar to Perl’s associative array Key value = string Unordered set of [ key : value ] pairs (2013-1) Understanding of Programming Languages 20 >>> grade_1 = { 'Kim' : 'A+', 'LeeHJ' : 'B', 'ChoiKK' : 'C+' } >>> grade_1[‘Kim’] ‘A+’ >>> grade_2 = dict([('KHH', 77), ('LYY', 89), ('CHH', 90)]) >>> grade_2 {'KHH': 77, 'LYY': 89, 'CHH': 90} >>> grade_3 = dict(KHH=77, LYY=89, CHH = 90) >>> grade_3 {'CHH': 90, 'LYY': 89, 'KHH': 77}
21
2. DATA TYPES (14): DICTIONARIES Operations: insert, delete (2013-1) Understanding of Programming Languages 21 >>> grade_1['AhnKK'] = 'D'# 삽입 >>> grade_1 {'LeeHJ': 'B', 'ChoiKK': 'C+', 'AhnKK': 'D', 'Kim': 'A+'} >>> del grade_1['ChoiKK']# 삭제 >>> grade_1 {'LeeHJ': 'B', 'AhnKK': 'D', 'Kim': 'A+'}
22
2. DATA TYPES (15): DICTIONARIES Contents output: for, items() (2013-1) Understanding of Programming Languages 22 >>> for name, point in grade_3.items(): print('name:', name, '=>', point) name: CHH => 90 name: LYY => 89 name: KHH => 77
23
3. CONTROL STATEMENTS if while for break continue (2013-1) Understanding of Programming Languages 23
24
(2013-1) Understanding of Programming Languages 24 >>> a = 0 >>> if a > 0: print("a is positive") elif a < 0: print("a is negative") else: print('a is zero') a is positive >>> a, sum = 0, 0# 1 >>> while a <= 10: sum += a a += 1 >>> print("sum =", sum) sum = 55 >>> a, sum=0,0 >>> while a<=10: sum += a a += 1 else: print(sum)# 1: 들여쓰기 주의 55
25
(2013-1) Understanding of Programming Languages 25 >>> Languages = [ ‘Python’, ‘Perl’, ‘Ruby’ ] >>> for aLang in Languages: print(aLang, len(aLang), end=" ")# 1 Python 6 Perl 4 Ruby 4 >>> aLang = Languages[0] >>> for ch in aLang: print(ch, end=" ")# 2 P y t h o n
26
(2013-1) Understanding of Programming Languages 26 range(n) : 0 ~ n-1 range(from, to) : from ~ to-1 range(from, to, step): from ~ to-1, step 만큼 증가 >>> sum1, sum2 = 0, 0 >>> for a in range(1, 11): sum1 += a >>> sum1 55 >>> for a in range(0, 11, 2): sum2 += a >>> sum2 30
27
(2013-1) Understanding of Programming Languages 27 >>> i, sum = 0, 0 >>> for i in range(1, 11): if i%3 == 0: break sum += i >>> print('i =', i, 'sum =', sum) i = 3 sum = 3 >>> i, sum = 0, 0 >>> for i in range(1, 11): if i%3 == 0: continue sum += i >>> print('i =', i, 'sum =', sum) i = 10 sum = 37
28
4. FUNCTION (1) Definition Call (2013-1) Understanding of Programming Languages 28 def function_name( parameter_list ) : function body >>> def calc_sum(n): a, sum = 0, 0 while a <= n: sum += a a += 1 print('sum from 1 to', n, 'is', sum) >>> calc_sum(10) sum from 1 to 10 is 55
29
4. FUNCTION (2) Default parameter value (2013-1) Understanding of Programming Languages 29 >>> def sum_100(start=1, end=100): sum = 0 while start <= end: sum += start start += 1 return sum >>> def calc_sum3(): print('sum_100() =', sum_100()) print('sum_100(99) =', sum_100(99)) print('sum_100(1, 10) =', sum_100(1, 10)) print('sum_100(end=10) =', sum_100(end=10))# 1 >>> calc_sum3() sum_100() = 5050 sum_100(99) = 199 sum_100(1, 10) = 55 sum_100(end=10) = 55# 2
30
5. FILE I/O File open: open(filename, mode); Read/write for file (2013-1) Understanding of Programming Languages 30 >>> aF = open('myInput.txt', 'r') >>> for aLine in aF: print(aL, end='') This is a sample file. I like the Python programming language. Let's try to learn the language!!! >>> aF.close()
31
(2013-1) Understanding of Programming Languages 31 >>> aF = open('myInput.txt', 'r') >>> str = aF.read()# str = aF.readlines() >>> str "This is a sample file.\nI like the Python programming language.\n Let's try to learn the language!!!" >>> aF.read()# read() 함수 ‘ >>> aF.close() >>> aF = open('myInput.txt', 'r') >>> aL = aF.readline() >>> while aL != '': print(aL, end='') aL = aF.readline()# readline() 함수 This is a sample file. I like the Python programming language. Let's try to learn the language!!!
32
(2013-1) Understanding of Programming Languages 32 >>> rFile = open('myInput.txt', 'r') >>> wFile = open('myOutput.txt', 'w') >>> content = rFile.read() >>> wFile.write(content) 98 >>> rFile.close() >>> wFile.close()
33
6. EXCEPTION HANDLING (1) Format (2013-1) Understanding of Programming Languages 33 try: 실행 코드 ( 실행 시간 에러가 발생할 수 있음 ) except: 사용자 정의 에러 복구 코드 else: 에러가 발생하지 않았을 경우 실행되는 코드 finally: 종료시 실행되는 코드
34
6. EXCEPTION HANDLING (2) Example (2013-1) Understanding of Programming Languages 34 >>> def divide(x, y): try: result = x / y except ZeroDivisionError: print('divide by 0 !!') else: print('result =', result) finally: print('division done...') >>> divide(10,4) result = 2.5 division done... >>> divide(6,0) divide by 0 !! division done...
35
7. MODULE Program file written in Python language File extension:.py (2013-1) Understanding of Programming Languages 35 >>> import sum >>> sum.sum_100()// 1 5050 >>> sum.calc_sum3()// 2 sum_100() = 5050 sum_100(99) = 199 sum_100(1, 10) = 55 sum_100(end=10) = 55
36
8. CLASS (1) class member: public Member function: virtual No member variable declaration (2013-1) Understanding of Programming Languages 36 class class_name: …
37
(2013-1) Understanding of Programming Languages 37 class MyFirstClass: def __init__(self, name=0, major=0): self.myName = name self.myMajor = major def introduce(self): myClass.py print('my name is', self.myName) print('my major is', self.myMajor) def my_message(self): return 'hello world !!!' >>> import myClass >>> aMan = myClass.MyFirstClass('KSD', 'Computer Engineering') >>> aMan.introduce() my name is KSD my major is Computer Engineering >>> aMan.my_message() 'hello world !!!'
38
8. CLASS (2) Single, multiple inheritance (2013-1) Understanding of Programming Languages 38 class Derived_Class_Name1(BaseClassName):# 단일 상속 … class Derived_Class_Name2(BaseClassName1, BaseClassName2):# 다중 상속 …
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.