** 파이썬 기초 과정 intro. (01) & (02) **
https://dataworld.tistory.com/58
https://dataworld.tistory.com/70
1. while 문
* intro. (01)에서 언급한 for문과 유사하다!
→ while문 strcture
#inital statement
while condition:
exectue_statement
increment/decrease_statement
→ while문 예시
i = 0
while i < 3:
print('hello world')
i = i +1
# hello world 0
# hello world 1
# hello world 2
→ %d / %i로 표시하기
- %i를 통해 변수 i를 받고, %d를 통해 해당 변수 i를 10진수 정수의 형태로 표현한다
- %s는 문자, %f는 소수를 받을 때 표현
count = int(input('반복횟수를 입력: '))
i = 0
while i < count:
print('hello world! %d', %i)
i = i+1
# 반복횟수를 입력: 2
# hello world! 0
# hello world! 1
→ random을 이용한 while 예제
- randint(a, b): a이상 b이하의 모든 정수를 '중복 허용하여' 랜덤으로 출력하는 method
import random
i = 0
while i != 3:
i = random.randint(0,9)
print(i)
#5 8 4 2 1 3
#3을 출력하면 종료되는 예제
2. break & continue
→ break문) 가장 가까운 반복문을 종료한다
- 반복문이 아닌 if문에는 영향을 미치지 않는다
for i in range(0,10):
print(i)
if i == 5:
break
#0 1 2 3 4 5
- i가 5가 되는 순간 break에서 제일 가까운 반복문 for loop에서 나가게 된다
→ continue문) 아래 코드로 진행되지 않고 위 조건으로 올라간다
for i in range(1,11):
if i%2 != 0:
continue
print(i)
#2 4 6 8 10
- continue를 만난 순간 해당 i는 아래 줄 print하지 않고 바로 위 for 구문으로 올라간다
→ continue & break 예제
Q) 1~20 사이의 숫자 중에서 3으로 끝나는 숫자 출력하기
A) code
i = 0
while True:
if i%10 !=3:
i = i +1
continue
if i > 20:
break
print(i, end = ' ')
i = i +1
#3 13
3. 파일 처리
* open - 파일 열기
<파일 객체> = open(<문자열: 파일 경로>, <문자열: 읽기 모드>)
* close - 파일 닫기
<파일 객체>.close()
* mode 종류
→ w(write): 기존 파일이 있으면 덮어쓰기 (기존 데이터 삭제) / 없으면 새로 만들어서 저장
→ a(append): 기존 파일이 있으면 내용의 뒷쪽 부분에 붙여서 표현
→ r(read): 읽기 전용모드
Q1) 텍스트파일 open하고 문자열 쓰기
#basic.txt 텍스트 파일 열기
file = open("basic.txt", "w")
#텍스트 파일에 원하는 문자열을 쓸 수 있다
file.write("hello python programming")
file.close()
Q2) with 사용
with open(파일 경로, mode) as 파일객체: 실행구문
- with문을 쓰면 따로 file을 close할 필요 없음! (very 편리)
* write
with open("basic.txt","w") as file:
file.write('hello python')
* read
with open("basic.txt", "r") as file:
contents = file.read()
print(contents)
#hello python
→ 한글 내용을 가져올 경우 encoding = "utf-8" 추가
with open("info.txt", "r", encoding = "utf-8") as file:
contents = file.read()
print(contents)
#name,age,job
#"김파이썬",20,"학생"
→ 파일 안의 내용 중 쉼표를 제외하여 원하는 내용만 가져오고 싶으면
↓ for loop & split 사용 (case by case)
with open("info.txt","r", encoding="utf-8") as file:
for line in file:
name, age, job = line.strip().split(", ")
print(job)
#job
#"학생"
→ 다른 경로의 파일을 가져오고 싶을 경우
- 상위 폴더는 ../
- 현재 경로는 ./
* append
with open("basic.txt","a") as file:
file.write("bye python")
#bye python이라는 내용이 basic.txt에 붙여진다.
4. 예외 처리
→ 구문오류) 프로그램 실행 전에 발생 (문법오류)
- 괄호의 갯수
- 들여쓰기 문제 (python 기본 문법)
→ 예외) 프로그램 실행 후에 발생
- 해당 예외는 if~else 조건문 & try ~ except 사용
- try는 항상 except와 함께
- 예외 클래스들은 상속에 의한 계층관계를 가지고 있기 때문에 상위 클래스를 사용하면 하위클래스 내용의 에러를 모두 잡을 수 있다
* 예외 종류
- NameErrror: 정의되지 않은 변수 사용 시 나타남
- ZeroDivisionError: 0으로 숫자를 나눌 때 나타남 (예외가 발생하면 프로그램 바로 종료)
- TypeError: 문자열과 숫자 더하기와 같이 다른 타입을 더할 때 발생
- IndexError: 참조 범위를 넘어서 index 사용 시 나타남
- KeyError: 등록되지 않은 key로 사전 검색 시 나타남
- IOError: 있지 않은 file을 열려고 할 때 나타남
ex) try ~ except
try:
number_input = int(input("정수 입력> "))
print('원의 반지름: ', number_input)
except:
print('숫자 데이터를 입력해주세요')
ex) try ~ except ~ else
- try에서 예외가 발생하면 except 문으로, 예외가 발생하지 않으면 else문 실행
- else문은 except 없이 사용 불가능하다
try:
number_input_a = int(input("정수 입력> "))
except:
print("정수를 입력해주세요.")
else:
print("원의 반지름", number_input_a)
ex) try ~ except ~ else ~ finally
- finally 구문은 무조건 실행
try:
number_input_a = int(input("정수 입력> "))
except:
print("정수를 입력해주세요.")
else:
print("원의 반지름", number_input_a)
finally:
print("프로그램 종료")
* 출처) 2021 공공데이터 청년인턴(일경험수련생) 상시교육
'Python > Fundamentals' 카테고리의 다른 글
시계열 데이터 - datetime (0) | 2022.03.24 |
---|---|
list comprehension (0) | 2022.03.20 |
Module & Package (0) | 2022.03.19 |
python intro. (02) (0) | 2022.03.18 |
python intro. (01) (0) | 2022.03.18 |
댓글