PY | 내장 함수 모음

Stellar·2023년 11월 2일
0

Python

목록 보기
29/36

내장 함수

✔️ 애스키 코드 변환.

>>> chr(65)
'A'
>>> ord('A')
65

✔️ complex(), 복소수를 반환

복소수 참고

>>> x = complex(4, 2)
>>> x
(4+2j)

✔️ dir(), 객체가 가지고 있는 함수를 보여준다.

>>> dir([])
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> dir(())
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

✔️ divmod(), 몫과 나머지를 한번에 보여 줌.

divmod(10,3)
(3, 1)

✔️ eval(), 문자열 수식을 계산하는 무서운 기능

eval() 함수는 문자열인 수식도 알아서 계산식으로 바꿔준다. 하지만 접근 불허한 디렉토리도 접근이 가능해 보안에 아주 취약하다. 또한 의존성을 주어 코드에 악영향을 미치므로 되도록 사용하지 말아야한다.
python eval() 함수 - 사용을 조심해야 하는 이유

>>> exp=input('파이썬의 수식을 입력하시오: ')
파이썬의 수식을 입력하시오: 2**10
>>> eval(exp)
1024

✔️ exec(), 엑스큐션, eval과 달리 값을 도출하진 않지만 식은 저장 됨.

>>> exec('y = 2 + 3')
>>> 
>>> y
5

사용 예제.

>>> statements = '''
... import math
... 
... def area_of_circle(radius) :
...     return math.pi*radius**2
... '''
>>> statements
'\nimport math\n\ndef area_of_circle(radius) :\n    return math.pi*radius**2\n'
>>> exec(statements)
>>> area_of_circle(5)
78.53981633974483

✔️ iter(), 반복되는 객체

class MyCounter(object) :
    #생성자 메소드를 정의.
    def __init__(self, low, high) :
        self.current = low
        self.high = high

    #이터레이터 객체로서 자신을 반환.
    def __iter__(self) :
        return self

    def __next__(self) :
        #current가 high 보다 크면 StopIteration 예외 발생.
        #current가 high 보다 작으면 다음 값을 반환.
        if self.current > self.high :
            raise StopIteration
        else :
            self.current += 1
            return self.current -1

c = MyCounter(1, 10)
for i in c :
    print(i, end=' ')
print()

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in list :
    print(i, end=' ')

iter 예제. foriter

nums = [11, 22, 33]
it = iter(nums)
while True :
    try :
        num = next(it)
    except StopIteration :
        break
    print(num)

iter 예제2. classiter

class Seq:
    def __init__(self, data) :
        self.data = data
        self.index = -2
    def __iter__(self) :
        return self
    def __next__(self) :
        self.index += 2
        if self.index >= len(self.data) :
            raise StopIteration
        return self.data[self.index:self.index + 2]

solarterm = Seq('입춘우수경칩춘분청명곡우입하소만망종하지소서대서')
for k in solarterm :
    print(k, end=' ')

✔️ 변수 맞교환

다른 언어와 다르게 파이썬은 빈 변수없이 변수끼리 맞교환이 가능하다.

x = 0
y = 7
x, y = y, x
print(x, y)

#----------------------
7 0

✔️ 상수(Constant)는 대문자 암묵적 룰

변치 않는 값을 저장하는 상수는 대문자로 사용할 것.

✔️ type() 자료형 알기

>>>type("hello world")
<class 'str'>
>>>type(1)
<class 'int'>
>>>type(2.3)
<class 'float'>

✔️ 메모리 주소 알기

>>> x = 10
>>> y = x
>>> id(x)
1714464096784 #x의 주소
>>> id(y)
1714464096784 #y에 x를 대입하여 똑같은 주소를 가르킨다.

✔️ 블록

파이썬은 다른 언어와 다르게 중괄호로 묶지 않는 대신 들여쓰기로 블록을 구분하기에 중요하다.

✔️ zip() 함수, zip 해제까지

짝을 지어 출력 후 남는 요소는 출력되지 않는다.

zip 예제.

>>> yoil = ['월', '화', '수', '목', '금', '토', '일']
>>> food = ['갈비탕', '순대국', '파전', '감자탕', '칼국수']
>>> menu = zip(yoil, food)
>>> for y, f in menu :
...     print('{}요일 메뉴 : {}'.format(y, f))
... 
월요일 메뉴 : 갈비탕
화요일 메뉴 : 순대국
수요일 메뉴 : 파전
목요일 메뉴 : 감자탕
금요일 메뉴 : 칼국수
>>> print(dict(zip(yoil, food))) #dict 타입으로도 출력 가능하다.
{'월': '갈비탕', '화': '순대국', '수': '파전', '목': '감자탕', '금': '칼국수'}

unzip 예제. *을 사용한다.

>>> un_tst = [('사과', 'apple'), ('바나나', 'banana'), ('오렌지', 'orange')]
>>> print(*un_tst)
('사과', 'apple') ('바나나', 'banana') ('오렌지', 'orange')
>>> print(zip(*un_tst))
<zip object at 0x104faac00>
>>> print(list(zip(*un_tst)))
[('사과', '바나나', '오렌지'), ('apple', 'banana', 'orange')]

✔️ any(), all() 불리언 값으로 반환 됨.

  • any : 하나라도 True면 됨.
  • all : 전부 True여야 함.

any, all 예제.

adult = [True, False, True, True]

print(any(adult))
print(all(adult))

✔️ filter(), 필요한 것만 골라내자.

filter() 함수는 걸러낸다기 보다, 원하는 값만 추려내는 것.
많이 사용 됨.
for문에 fliter()함수를 쓰고 안에 외부 함수와 시퀀스 객체를 넣어 사용한다.

filter 예제.

def flunk(s) :
    return s < 60

score = [45, 90, 82, 53, 94]
for s in filter(flunk, score) : #flunk 함수에서 값을 걸러줌.
    print(s)

filter 예제2.

list = []

def test(a):
    if a % 6 == 0 :
        list.append(a)
    else:
        pass

for i in filter(test, range(1, 100)) :
    print()

print(list)

제어 관련 주요 명령어, 고급 문법

✔️ break

중단하라.

#break
score = [92, 86, 68, 120, 56]

for i in score :
    if (i < 0) or (i >100) :
        break
    print(i)
print('성적 처리 끝')

✔️ continue

무시하고 계속하라.

#continue
score = [92, 86, 68, 120, 56]

for i in score :
    if (i < 0) or (i >100) :
        continue
    print(i)
print('성적 처리 끝')

0개의 댓글