본문 바로가기

PYTHON

Docstring, Scope, Module, File I/O 개념

* 자료구조(data struct) : 다양한 방식으로 데이터를 모아둔 것

* list, dictionary 는 모든 타입 가능

* 시퀀스 : 데이터가 나열되어 있는 형태

 

* None type : 데이터가 없다. (= 다른 언어에서의 NULL)

* 더미 변수 : _ (언더바)

 

* // : 나눗셈 후, 소수점을 버리는 연산자

 

Fuction

docstring : 함수 주석, 마우스를 갖다대면 뜨는 노란창

def iseven(n):
	''' 
	(docstring)
	짝수인지 확인하는 함수
	'''
	if n%2==2:
		return True

print(iseven(7))

 

#실습1

키와 몸무게를 입력받아 BMI 지수 계산

def calBMI(height, weight):
    '''
    height : 키
    weight : 몸무게
    '''
    bmi = weight/height**2

    if bmi >= 35:
        result = '고도비만'
    elif bmi >= 30:
        result = '중도 비만 (2단계 비만)'
    elif bmi >= 25:
        result = '경도 비만 (1단계 비만)'
    elif bmi >= 23:
        result = '과체중'
    elif bmi>= 18.5:
        result = '정상'
    else:
        result = '저체중'
    
    
    return bmi, result

b,st = calBMI(1.8, 80)
print(f'BMI: {b:.2f}, 비만정도 : {st}')

 

Scope(범위)

local variable : 함수 내에서 사용할 수 있는 변수

gobal variable : 전역에서 사용할 수 있는 변수

 

global variable은 함수 내에서 수정(변형)x, 참조(가져다쓰기)만 가능하다.

def f(y):
    x = 1
    x += 1
    print(x) #local variable

x = 5
f(x)
print(x) #local variable


def g(y):
    print(x)
    print(x+1)

x = 5
g(x)
print(x) #local variable


# UnboundLocalError: local variable 'x' referenced before assignment
# global variable은 함수 내에서 변형x, 가져다쓰기만 가능하다.
# def h(y):
#     x += 1
def h(y):
	global x
    x += 1

x = 5
h(x)
print(x) #local variable

>>> 2
>>> 5
>>> 5
>>> 6
>>> 5
>>> 6
# function 1
x = 300
def f1():
    x = 200
    print(x)

f1()
print(x)

# function 2
def f2():
    global x
    x = 300

f2()
print(x)

# function 3
x = 300
def f3():
    global x
    x = 200

f3()
print(x)

>>> 200
>>> 300
>>> 300
>>> 200
x = 100

'''
# error code
def f1():
	# 여기서는 x를 직접 수정하지 않고 가져다 사용하기 때문에 오류가 나지 않는다.
    y = x+200
    # UnboundLocalError: local variable 'x' referenced before assignment
    x//=2
    return y

print(f'f1: {f1()}') #150
'''

# 수정한 코드
def f1():
    global x
    y = x+200
    y//=2
    return y

print(f'f1: {f1()}') #150

 

module

  • import
    • import random
    • import os
  • 라이브러리(library)
  • 파이썬 파일명 random.py
  • 표준 라이브러리
    • 별도 설치없이 사용
    • 만들어진 코드를 가져와서 사용하는 것
  • 같은 폴더 안에 위치해있어야 import 가능.
import random

x = random.randint(1, 100)
print(x)

 

as를 이용하여 random의 별명을 지어 사용

import random as rd

x = rd.randint(1, 100)
print(x)

 

일부 함수만 가져올 경우

from random import randint

x = randint(1, 100)
print(x)

 

* 가져온 모듈 내의 함수와 같은 이름으로 함수를 만들 경우,

내가 만든 함수로 바뀜, 그렇기 때문에 같은 이름 함수 만들지x

 

* : 모든 함수

from random import *

x = randint(1, 100)
print(x)

 

sub 폴더 안에 파일을 위치시켜 import

from sub import math as m

m._add(2,3)
# Choice
# ['가위', '바위', '보']
# 컴퓨터 vs 나
# 컴퓨터 : random
# 나 : input('가위', '바위', '보')
# loop를 이용하여 삼세판
# (삼세판의 정의가 많아서 3판 먼저 이긴사람이 승으로 설정)

import random as r

# 나와 컴퓨터의 이긴 횟수를 저장하는 변수
m_win = 0
c_win = 0

while 1:
    # 3판 이기는 사람이 생기면 결과 도출
    if m_win== 3 or c_win == 3:
        if m_win == 3:
            print("[결과] 내가 이겼습니다~ 짝짝짝")
        else:
            print("[결과] 컴퓨터에게 졌습니다 ㅠㅠ 다시 도전해보세요.")

        break;
    
    computer = r.choice(['가위', '바위', '보'])

    my = input('가위, 바위, 보 중 하나를 내주세요 : ')
    print('computer : ', computer)

    if my == '가위':
        # 컴퓨터가 가위 일때 비김
        # 컴퓨터가 바위 일 때 짐
        # 컴퓨터가 보일때 이김
        if computer == '가위':
            print('비겼습니다.\n')
        elif computer == '바위':
            c_win += 1
            print('졌습니다ㅠㅠ\n')
        elif computer == '보':
            m_win += 1
            print('이겼습니다!\n')

    elif my == '바위':
        if computer == '가위':
            m_win += 1
            print('이겼습니다!\n')
        elif computer == '바위':
            print('비겼습니다.\n')
        elif computer == '보':
            c_win += 1
            print('졌습니다ㅠㅠ!\n')

    elif my == '보':
        if computer == '가위':
            c_win += 1
            
            print('졌습니다ㅠㅠ\n')
        elif computer == '바위':
            m_win += 1
            print('이겼습니다!\n')
        elif computer == '보':
            print('비겼습니다.\n')

 

File I/O

  • Text File
    • Text(.txt, .py)
  • Binary File
    • Image
    • Spread Sheet
    • 실행프로그램(photoshop, excel 등)으로 볼 수 있다.

 

    Open

   ↙       ↘

Read    Write

  ↘        ↙

    Clocse

 

  • fhandle = open(filename, mode)
  • [ 파일핸들 파일명(문자열) 모드(읽기, 보기) ]
  • File Mode
    • r : read (default)
    • w : write
    • a: append  
       filename = 'romeo.txt'
       f = open (filename, r)
  • File Open
    • FileNotFound
    • 텍스트 파일과 파이썬 파일이 같은 폴더에 위치해있어야 함.
  • 경로
    • 절대경로
    • 상대경로

 

'PYTHON' 카테고리의 다른 글

Pandas  (0) 2021.12.03
File I/O, 예외처리 개념  (0) 2021.11.19
Set, 집합, Function, Parameter, Argument, Return 개념  (0) 2021.11.05