|
|
beginning programming with python 을 읽었다. 우선 파이선 홈피에서 윈도64용을 다운받았다. 42 print("")로 시험하고 quit()로 종료했다. 54=38+16/36 파이썬 기초 문법 정리:
1. 출력 (print); print("Hello, Python!") print(10, 20)
2. 변수 (Variables); 파이썬은 변수 타입을 따로 선언하지 않는다. name = "Alice" age = 20 height = 165.5
3. 자료형 (Data Types)
### 기본 자료형; a = 10 # int b = 3.14 # float c = "hi" # str d = True # bool
### 리스트(list); numbers = [1, 2, 3] print(numbers[0]) # 1
### 딕셔너리(dict);person = {"name": "Tom", "age": 25} print(person["name"])
4. 조건문 (if / elif / else);age = 18 if age >= 20: print("성인입니다.") elif age >= 13: print("청소년입니다.") else: print("어린이입니다.")
5. 반복문 (for / while);
### for; for i in range(5): print(i)
### while; count = 0 while count < 3: print(count) count += 1
6. 함수 (function); def add(a, b): return a + b print(add(3, 5))
7. 입력 (input); name = input("이름을 입력하세요: ") print("안녕하세요,", name)
8. 주석 (comments); # 한 줄 주석 """여러 줄 주석""" 56=40+16
testme = 6
if testme == 6:
print("testme does equal 6!") 134
Value = int(input("Type a number between 1 and 10: "))
if (Value > 0) and (Value <= 10):
print("You typed: ", Value) 138
Value = int(input("Type a number between 1 and 10: "))
if (Value > 0) and (Value <= 10):
print("You typed: ", Value)
else:
print("The value you typed is incorrect!") 141
print("1. Red")
print("2. Orange")
print("3. Yellow")
print("4. Green")
print("5. Blue")
print("6. Purple")
Choice = int(input("Select your favorite color: "))
if (Choice == 1):
print("You chose Red!")
elif (Choice == 2):
print("You chose Orange!")
elif (Choice == 3):
print("You chose Yellow!")
elif (Choice == 4):
print("You chose Green!")
elif (Choice == 5):
print("You chose Blue!")
elif (Choice == 6):
print("You chose Purple!")
else:
print("You made an invalid choice!") 142
One = int(input("Type a number between 1 and 10: "))
Two = int(input("Type a number between 1 and 10: "))
if (One >= 1) and (One <= 10):
if (Two >= 1) and (Two <= 10):
print("Your secret number is: ", One * Two)
else:
print("Incorrect second value!")
else:
print("Incorrect first value!") 145
LetterNum = 1
for Letter in "Howdy!":
if Letter == "w":
continue
print("Encountered w, not processed.")
print("Letter ", LetterNum, " is ", Letter)
LetterNum+=1 155
while statement behavior:
✓ break: Ends the current loop.
✓ continue: Immediately ends processing of the current element.
✓ pass: Ends processing of the current element after completing the statements in the if block.
✓ else: Provides an alternative processing technique when conditions aren’t met for the loop.
Sum = 0
while Sum < 5:
print(Sum)
Sum+=1 160
프로그래밍에서 시맨틱 오류(semantic error)는 코드가 문법적으로는 맞아서 실행은 되지만, 개발자가 의도한 의미와 다르게 동작하는 오류다. 즉, 컴파일러나 인터프리터는 통과하지만 논리적으로 틀린 오류다. 문법(syntax)은 맞아 실행 가능하지만 의미(semantics)가 잘못되었기에 결과가 의도와 다르다. 주로 논리 오류(logic error)와 비슷하게 사용된다.
🔍 예시 1 — 잘못된 연산
```python
a = 5
b = 3
result = a * b # 사실은 더하려고 했지만 * 사용
print(result)
```
🔍 예시 2 — 잘못된 조건문
```python
age = 20
if age < 18: # >=여야 했음
print("성인입니다.")
```
🔍 예시 3 — 변수 사용 실수
```python
total = price + tax
print(prcie) # price와 다른 변수 사용
```
🔍 예시 4 — 인덱스나 반복 범위 오류
```python
numbers = [1, 2, 3]
for i in range(4): # range(3)이 맞음
print(numbers[i])
```
👍 시맨틱 오류를 찾는 방법
* 디버깅: 출력값 확인, breakpoints
* 테스트 작성: 예상 입력/출력 비교
* 코드 리뷰: 사람 눈으로 논리 확인
* 변수 이름 명확히 하기 170
try:
Value = int(input("Type a number between 1 and 10:
"))
except ValueError:
print("You must type a number between 1 and 10!")
else:
if (Value > 0) and (Value <= 10):
print("You typed: ", Value)
else:
print("The value you typed is incorrect!") 172
try:
File = open('myfile.txt')
except IOError as e:
print("Error opening file!\r\n" +
"Error Number: {0}\r\n".format(e.errno) +
"Error Text: {0}".format(e.strerror))
else:
print("File opened as expected.")
File.close(); 178
class CustomValueError(ValueError):
def __init__(self, arg):
self.strerror = arg
self.args = {arg}
try:
raise CustomValueError("Value must be within 1 and 10.")
except CustomValueError as e:
print("CustomValueError Exception!", e.strerror) 193
import sys
try:
raise ValueError
print("Raising an exception.")
except ValueError:
print("ValueError Exception!")
sys.exit()
finally:
print("Taking care of last minute details.")
print("This code will never execute.") 195
모듈을 가져오는 방법에는 두 가지가 있다. .
✓ import: 전체 모듈을 가져오려면 import 문을 사용한다.
이 방법은 개발자가 모듈을 가져오는 데 가장 일반적으로 사용하는 방법으로, 시간을 절약하고 한 줄의 코드만 필요하기 때문이다. 하지만 이 방법은 필요한 속성만 선택적으로 가져오는 방법보다 메모리 리소스를 더 많이 사용한다.
✓ frohttp://m...import: 개별 모듈 속성을 선택적으로 가져오려면 frohttp://m...import 문을 사용한다.
이 방법은 리소스를 절약하지만 복잡성이 증가한다. 또한 가져오지 않은 속성을 사용하려고 하면 Python에서 오류가 발생한다. 모듈에는 여전히 해당 속성이 포함되어 있지만 Python에서 해당 속성을 볼 수 없다.
현재 Python 디렉터리 변경
Python이 코드에 액세스하는 데 사용하는 디렉터리는 로드할 수 있는 모듈에 영향을 미친다. Python 라이브러리 파일은 항상 Python이 액세스할 수 있는 위치 목록에 포함되지만, Python은 사용자가 소스 코드를 저장하는 디렉터리를 확인하도록 지정하지 않는 한 해당 디렉터리에 대해 아무것도 알지 못한다.
이 작업을 수행하는 가장 쉬운 방법은 다음 단계에 따라 현재 Python 디렉터리가 코드 폴더를 가리키도록 변경하는 것이다.
1. Python 셸을 연다.
2. import os를 입력하고 Enter 키를 누른다.
이 작업을 수행하면 Python os 라이브러리가 가져온다. 디렉토리(Python이 디스크에서 인식하는 위치)를 이 책의 작업 디렉터리로 변경하려면 이 라이브러리를 가져와야 한다.
3. os.chdir("C:\BP4D\Chapter10")을 입력하고 Enter 키를 누른다.
다운로드 가능한 소스 또는 로컬 하드 드라이브에 있는 자체 프로젝트 파일이 있는 디렉터리를 사용해야 한다. 이 책은 4장에서 설명한 기본 책 디렉터리를 사용합니다. 이제 Python은 다운로드 가능한 소스 코드 디렉터리를 사용하여 이 장에서 생성한 모듈에 액세스할 수 있다. 202
✓ import: import MyLibrary를 입력한다. Python은 모듈의 캐시를 __pycache__ 하위 디렉터리에 생성한다는 점을 알아두는 것이 중요하다. MyLibrary를 처음 임포트한 후 소스 코드 디렉터리를 살펴보면 새로운 __pycache__ 디렉터리가 표시된다. 모듈을 변경하려면 이 디렉터리를 삭제해야 한다. 그렇지 않으면 Python은 업데이트된 소스 코드 파일 대신 변경되지 않은 캐시 파일을 계속 사용한다.
4. dir(MyLibrary)를 입력하고 Enter 키를 누른다. 그림 10-1과 같이 SayHello() 및 SayGoodbye() 함수가 포함된 모듈 내용 목록이 표시된다. (다른 항목에 대한 설명은 이 장의 "모듈 내용 보기" 섹션에 있다.) 203
5. MyLibrary.SayHello(“Josh”)을 입력한다. 204
✓ frohttp://m...import: from MyLibrary import SayHello, SayGoodbye) or to use the asterisk(*) in place of a specific attribute name. 205
파이썬에서 모듈(module)과 애트리뷰트(attribute)는 코드 구조를 이루는 핵심 개념이다.
1. 모듈(Module); 파이썬 코드(함수, 클래스, 변수 등)를 담고 있는 파일(.py). 코드를 여러 파일로 나눠서 재사용하거나 유지보수하기 쉽게 만든다.
✔ 예시: `math` 모듈
```python
import math
print(math.sqrt(9)) # 3.0
```
✔ 모듈을 만드는 법
`mymodule.py`
```python
def hello():
print("Hello!")
```
사용하기:
```python
import mymodule
mymodule.hello()
```
2. 애트리뷰트(Attribute); 모듈, 함수, 클래스, 객체 등에 속한 이름(값).
> 모듈 안에 들어있는 함수, 변수, 클래스 등 → 모듈의 애트리뷰트
> 객체 안에 들어있는 변수, 메서드 → 객체의 애트리뷰트
✔ 예시: 모듈의 애트리뷰트
```python
import math
print(math.pi) # 애트리뷰트 (변수)
print(math.sin) # 애트리뷰트 (함수)
```
여기서 `pi`, `sin`은 `math` 모듈의 애트리뷰트.
3. 애트리뷰트 확인하기; 파이썬 내장 함수 `dir()`로 객체의 모든 애트리뷰트를 확인할 수 있다.
```python
import math
print(dir(math))
```
4. 모듈 vs 패키지
| 모듈 | `.py` 파일 하나 |
| 패키지 | 여러 모듈을 폴더 구조로 묶은 것 (`__init__.py` 포함) |
✨ 예시
다음과 같은 구조가 있을 때:
```
mymath/
__init__.py
calc.py
```
`calc.py`
```python
PI = 3.14
def area(r):
return PI * r * r
```
사용:
```python
from mymath import calc
print(calc.PI) # calc 모듈의 애트리뷰트
print(calc.area(3))
``` 221
1. Open a Python Shell window. You see the familiar Python prompt.
2. Type List1 = [“One”, 1, “Two”, True] and press Enter.
Python creates a list named List1 for you. This list contains two string values (One and Two), an integer value (1), and a Boolean value (True). 242
✓ append(): Adds a new entry to the end of the list. ✓ pop(): Removes an entry from the end of the list. ✓ extend(): Adds items from an existing list and into the current list.
✓ clear(): Removes all entries from the list. ✓ copy(): Creates a copy of the current list and places it in a new list.
✓ insert(): Adds a new entry to the position specified in the list. ✓ remove(): Removes an entry from the specified position in the list. 243
Type List1.append(1) and press Enter. Type List1.pop(1) and press Enter. 248
Type List1.insert(0, 2) and press Enter. The insert() function requires two arguments. The first argument is the index of the insertion, which is element 0 in this case.
The second argument is the object you want inserted at that point, which is 2 in this case. 250
Type List2 = List1.copy() and press Enter. The new list, List2, is a precise copy of List1.
Type List1.extend(List2) and press Enter. Python copies all the elements in List2 to the end of List1. Extending is commonly used to consolidate two lists.
Type List1 and press Enter. You see that the copy and extend processes have worked. List1 now contains the values 2, 1, 2, and 1.
Type List1.pop() and press Enter. Python displays a value of 1. The 1 was stored at the end of the list, and pop() always removes values from the end.
Type List1.remove(1) and press Enter. This time, Python removes the item at element 1. Unlike the pop() function, the remove() function doesn’t display the value of the item it removed.
Type List1.clear() and press Enter. Using clear() means that the list shouldn’t contain any elements now. 251
리스트(list)와 튜플(tuple)은 파이썬에서 여러 값을 담을 수 있는 자료형이지만, 중요한 차이들이 있다.
✅ 리스트(list)
✔ 변경 가능(mutable)
✔ 대괄호 `[]` 사용
✔ 값 추가/삭제/수정 가능
### 예시
```python
a = [1, 2, 3]
a[0] = 10 # 수정 가능
a.append(4) # 값 추가
print(a) # [10, 2, 3, 4]
```
✅ 튜플(tuple)
✔ 변경 불가능(immutable)
✔ 소괄호 `()` 사용
✔ 한 번 만들면 내부 값을 바꿀 수 없음
✔ 리스트보다 메모리 적게 사용하고 속도가 빠름
### 예시
```python
b = (1, 2, 3)
# b[0] = 10 # ❌ 오류 발생 (수정 불가)
print(b) # (1, 2, 3)
```
📌 차이점 정리
| 구분 | 리스트(list) | 튜플(tuple) |
| 변경 가능 여부 | O (가능) | X (불가능) |
| 기호 | `[]` | `()` |
| 속도 | 느림 | 빠름 |
| 사용 용도 | 자주 바뀌는 데이터 | 고정된 데이터 |
| 메모리 사용량 | 많음 | 적음 |
📘 언제 리스트? 언제 튜플?
### ✔ 리스트 추천
* 데이터가 계속 변할 때
* 추가/삭제/정렬이 필요할 때
### ✔ 튜플 추천
* 데이터를 절대 바꾸지 않아야 할 때
* 속도/메모리 최적화가 필요할 때
* 함수에서 여러 값을 반환할 때 261
Type MyTuple = (“Red”, “Blue”, “Green”) and press Enter. Python creates a tuple containing three strings.
Type MyTuple and press Enter. You see the content of MyTuple, which is three strings.
Type dir(MyTuple) and press Enter. Python presents a list of functions that you can use with tuples
Type MyTuple = MyTuple.__add__((“Purple”,)) and press Enter. This code adds a new tuple to MyTuple and places the result in a new copy of MyTuple. The old copy of MyTuple is destroyed after the call.
The __add__() function accepts only tuples as input. This means that you must enclose the addition in parentheses.
Type MyTuple and press Enter. The addition to MyTuple appears at the end of the list
Type MyTuple = MyTuple.__add__((“Yellow”, (“Orange”, “Black”))) Enter. This step adds three entries: Yellow, Orange, and Black. However, Orange and Black are added as a tuple within the main tuple, which creates a hierarchy.
Type MyTuple[4] and press Enter. Python displays a single member of MyTuple, Orange. Tuples use indexes to access individual members, just as lists do.
Type MyTuple[5] and press Enter. You see a tuple that contains Orange and Black. 263
Type MyTuple[5][0] and press Enter. At this point, you see Orange as output. 264
리스트(list)와 사전(dictionary, dict)는 여러 데이터를 저장하는 파이썬의 대표적인 자료구조이지만, 저장 방식과 사용 목적이 크게 다르다.
✅ 리스트(list)
✔ 순서가 있는 데이터 구조 (ordered)
✔ 인덱스로 접근 (0, 1, 2 …)
✔ 대괄호 `[]` 사용
✔ 값 중복 허용
### 예시
```python
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # banana
```
✅ 사전(dictionary, dict)
✔ 키(key)-값(value) 쌍으로 저장
✔ 순서는 있지만(파이썬3.7+), 인덱스로 접근 불가
✔ 중괄호 `{}` 사용
✔ 키는 중복 불가, 값은 중복 가능
### 예시
```python
person = {"name": "Alice", "age": 25}
print(person["name"]) # Alice
```
📌 차이점
| 구분 | 리스트(list) | 사전(dict) |
| 저장 방식 | 값(value)만 저장 | 키(key)-값(value) 쌍 저장 |
| 접근 방식 | 인덱스 번호로 접근 | 키(key)로 접근 |
| 순서 | 있음 | 있음(3.7+) |
| 중복 | 값 중복 가능 | 키 중복 불가 |
| 속도 | 인덱스 접근 빠름 | 키 기반 탐색 매우 빠름 |
| 대표 용도 | 순서가 중요한 데이터 | 의미(이름)가 중요한 데이터 |
📘 언제 리스트? 언제 사전?
✔ 리스트(list) 추천
* 순서가 중요한 경우
* 데이터가 단순히 나열되는 경우
* 인덱스로 반복 접근할 때
예: 학생 점수 목록 `[80, 90, 85]`
✔ 사전(dict) 추천
* 각 데이터에 ‘이름/의미’가 필요할 때
* 빠르게 특정 항목을 찾고 싶을 때
예:
```python
student = {"name": "Tom", "score": 90, "grade": "A"}
```
📚 예시 비교
✔ 리스트 예시
```python
users = ["Tom", "Jane", "Mike"]
```
✔ 사전 예시
```python
user = {
"id": 101,
"name": "Tom",
"email": "tom@example.com"
}
``` 265
큐(Queue)와 스택(Stack)은 데이터를 넣고 빼는 방식이 다른 자료구조다.
✅ 스택(Stack); LIFO 구조 → Last In, First Out(마지막에 들어간 것이 가장 먼저 나온다) ✔ ‘접시 쌓기’와 같은 구조
### 기능
* `push()` : 데이터 넣기
* `pop()` : 데이터 꺼내기
### 예시
```python
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop()) # 3 (마지막 값이 먼저 나옴)
```
✅ 큐(Queue); FIFO 구조 → First In, First Out(처음 들어간 것이 가장 먼저 나온다) ✔ ‘줄 서기’와 같은 구조
### 기능
* `enqueue()` : 데이터 넣기
* `dequeue()` : 데이터 꺼내기
### 예시 (deque 사용)
```python
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)
print(queue.popleft()) # 1 (먼저 들어간 값이 먼저 나옴)
```
📌 차이점 정리
| 구분 | 스택(Stack) | 큐(Queue) |
| 원리 | LIFO | FIFO |
| 사용 메서드 | push, pop | enqueue, dequeue |
| 비유 | 접시 더미 | 줄 서기 |
| 파이썬 구현 | `list`로 가능 | `deque` 권장 |
📘 언제 사용?
✔ 스택 사용
* 되돌리기 기능 (Undo)
* 웹 브라우저 방문 기록
* 재귀 구조 구현
✔ 큐 사용
* 대기열 처리 (프린터 큐)
* 너비 우선 탐색(BFS)
* 작업 스케줄링 276
파이썬의 클래스(Class)는 객체(Object)를 만들기 위한 설계도다. 클래스를 사용하면 관련된 데이터(속성)와 동작(메서드)을 하나로 묶어서 구조화된 프로그램을 만들 수 있다.
✅ 클래스란?
* 객체를 생성하기 위한 틀(Template) 또는 설계도
* 클래스에서 만든 객체를 인스턴스(instance) 라고 부름
* 속성(변수)과 메서드(함수)를 가질 수 있음
✅ 클래스 기본 형태
```python
class 클래스이름:
# 생성자
def __init__(self, 값1, 값2):
self.값1 = 값1 # 인스턴스 변수
self.값2 = 값2
# 메서드
def method(self):
print("메서드 실행")
```
🔰 간단한 예시
✔ 사람(Person) 클래스 만들기
```python
class Person:
def __init__(self, name, age): # 초기화 메서드(생성자)
self.name = name
self.age = age
def say_hello(self): # 메서드
print(f"안녕하세요, 저는 {self.name}입니다.")
```
✔ 객체(인스턴스) 생성
```python
p1 = Person("Tom", 20)
p1.say_hello() # 안녕하세요, 저는 Tom입니다.
```
📌 클래스의 핵심 요소 정리
| 클래스(class) | 객체를 생성하기 위한 설계도 |
| 객체(object) | 클래스로 만들어진 실제 데이터 |
| 인스턴스(instance) | 특정 클래스에서 만들어진 객체 |
| 속성(attribute) | 객체가 가지고 있는 값(변수) |
| 메서드(method) | 객체가 실행할 수 있는 함수 |
| self | 객체 자신을 참조 |
🧱 왜 클래스를 사용할까? (장점)
✔ 코드 재사용; 한 번 만든 클래스를 여러 번 쓸 수 있음.
✔ 구조화된 코드; 속성과 기능을 묶어서 관리하기 쉬움.
✔ 유지보수 편리; 코드가 객체 단위로 나뉘어 있어서 문제를 찾기 쉬움.
✔ 객체지향 프로그래밍(OOP) 구현; 상속, 캡슐화, 다형성 등을 활용 가능.
📚 심화 예시: 간단한 상속
```python
class Animal:
def sound(self):
print("동물이 소리를 냅니다")
class Dog(Animal): # Animal을 상속받음
def sound(self):
print("멍멍!")
d = Dog()
d.sound() # 멍멍!
``` 283
class MyClass:
def DoAdd(self, Value1=0, Value2=0):
Sum = Value1 + Value2
print("The sum of {0} plus {1} is {2}."
.format(Value1, Value2, Sum))
MyInstance = MyClass() and press Enter. Python creates an instance of MyClass named MyInstance.
MyInstance.DoAdd(1, 4) and press Enter. You see the sum of adding 1 and 4. 296
https://www.amazon.ca/Beginning-Programming-Python-Dummies-Mueller/dp/1118891457
Introduction ................................................................1
Part I: Getting Started with Python ...............................5
Chapter 1: Talking to Your Computer .............................................................................7
Chapter 2: Getting Your Own Copy of Python .............................................................21
Chapter 3: Interacting with Python ...............................................................................39
Chapter 4: Writing Your First Application ....................................................................57
Part II: Talking the Talk .............................................81
Chapter 5: Storing and Modifying Information ............................................................83
Chapter 6: Managing Information ..................................................................................93
Chapter 7: Making Decisions ........................................................................................117
Chapter 8: Performing Repetitive Tasks .....................................................................133
Chapter 9: Dealing with Errors .....................................................................................149
Part III: Performing Common Tasks ...........................181
Chapter 10: Interacting with Modules .........................................................................183
Chapter 11: Working with Strings ................................................................................205
Chapter 12: Managing Lists ..........................................................................................223
Chapter 13: Collecting All Sorts of Data ......................................................................243
Chapter 14: Creating and Using Classes .....................................................................267
Part IV: Performing Advanced Tasks .........................291
Chapter 15: Storing Data in Files ..................................................................................293
Chapter 16: Sending an E-Mail ......................................................................................309
Part V: The Part of Tens ...........................................327
Chapter 17: Ten Amazing Programming Resources ..................................................329
Chapter 18: Ten Ways to Make a Living with Py thon ...............................................339
Chapter 19: Ten Interesting Tools ...............................................................................347
Chapter 20: Ten Libraries You Need to Know About ................................................357
Index ......................................................................365
