SlideShare a Scribd company logo
파이썬 내장 함수
정보기술 시대에 유익한 파이썬 프로그래밍 – 제 6 강 (2)
동양미래대학교
2015.7
최용 <sk8er.choi@gmail.com>
내장 함수
Built-in Functions
Python3 내장 함수
Built-in Functi
ons
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()
https://docs.python.org/3/library/functions.html
abs()
>>> abs(-3)
3
>>> abs(-3.0)
3.0
>>> z = complex(1, 2)
>>> abs(z)
2.23606797749979
all()
>>> all([True, True, True])
True
>>> all([True, False, True])
False
any()
>>> any([True, False, True])
True
>>> any((False, False, False))
False
ascii()
>>> ascii('''Airbed
... Breakfast''')
"'AirbednBreakfast'"
>>> ascii('김치')
"'uae40uce58'"
bin()
>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
>>> bin(4)
'0b100'
bool()
>>> bool(True)
True
>>> bool(2 < 3)
True
>>> bool(1)
True
>>> bool(3 % 2)
True
>>> bool(not None)
True
>>> bool(False)
False
>>> bool(2 > 3)
False
>>> bool(0)
False
>>> bool(4 % 2)
False
>>> bool(None)
False
>>> bool()
False
bytearray()
>>> data = bytearray(b'Monty Python')
>>> data[5] = 33 # mutable
>>> data
bytearray(b'Monty!Python')
http://python3porting.com/problems.html#manipulating-binary-data
http://dabeaz.blogspot.kr/2010/01/few-useful-bytearray-tricks.html
bytes()
>>> b'Python'
b'Python'
>>> type(b'Python')
<class 'bytes'>
>>> b'파이썬'
File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> bytes('Python', 'utf-8')
b'Python'
>>> bytes('파이썬', 'utf-8')
b'xedx8cx8cxecx9dxb4xecx8dxac'
callable()
>>> def sum(x, y):
... return x + y
...
>>> callable(sum)
True
>>> x = 10
>>> callable(x)
False
>>> class MyClass:
... pass
...
>>> callable(MyClass)
True
>>> obj = MyClass()
>>> callable(obj)
False
http://joequery.me/code/python-builtin-functions/#callable
chr()
>>> chr(65)
'A'
>>> chr(97)
'a'
>>> chr(49)
'1'
classmethod()
>>> class Pizza:
... radius = 42
... @classmethod
... def get_radius(cls):
... return cls.radius
...
>>> Pizza.get_radius()
42
https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
compile()
>>> codeobj = compile('x = 2nprint("X is " + str(x))', # source
... 'fakemodule', # file name
... 'exec') # mode
>>> exec(codeobj)
X is 2
http://stackoverflow.com/questions/22443939/python-built-in-function-compile-what-is-it-used-for
complex()
>>> x = complex("4+2j")
>>> x
(4+2j)
>>> y = complex("4-5j")
>>> y
(4-5j)
>>> x+y
(8-3j)
>>> x*y
(26-12j)
>>> complex("4")
(4+0j) http://joequery.me/code/python-builtin-functions/#complex
delattr()
>>> class Employee:
... def __init__(self, name, salary):
... self.name = name
... self.salary = salary
...
>>> j = Employee("John", "2000$")
>>> j.salary
'2000$'
>>> delattr(j, "salary")
>>> hasattr(j, "salary")
False
dict()
>>> dict()
{}
>>> dict( [[1, 'a'], [2, 'b'], [3, 'c']] )
{1: 'a', 2: 'b', 3: 'c'}
>>> dict( ((1, 'a'), (2, 'b'), (3, 'c')) )
{1: 'a', 2: 'b', 3: 'c'}
dir()
>>> class Shape:
... def __dir__(self):
... return ['area', 'perimeter', 'location']
...
>>> s = Shape()
>>> dir(s)
['area', 'location', 'perimeter']
>>> import struct
>>> dir(struct)
['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pack
age__', '__spec__', '_clearcache', 'calcsize', 'error', 'iter_unpack', 'pack', 'pack_into', 'unpack', 'unpack_
from']
divmod()
>>> divmod(7, 3)
(2, 1)
>>> divmod(8.4, 4.2)
(2.0, 0.0)
>>> divmod(8.5, 4.2)
(2.0, 0.09999999999999964)
enumerate()
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
eval()
>>> x = 1
>>> eval('x + 1')
2
>>> y = eval('x + 2')
>>> y
3
>>> a = 10
>>> b = 5
>>> D = {'a': 2, 'b': 3}
>>> eval('a + b')
15
>>> eval('a + b', D)
5
exec()
>>> a = 3
>>> exec('b = 2') # eval()과 달리, 값을 리턴하지 않음
>>> exec('c = a + b')
>>> c
5
filter()
>>> N = range(1, 11)
>>> Even = list()
>>> for n in N:
... if n % 2 == 0:
... Even.append(n)
...
>>> Even
[2, 4, 6, 8, 10]
>>> Odd = list(filter(lambda x: x % 2, N))
>>> Odd
[1, 3, 5, 7, 9]
float()
>>> float(1)
1.0
>>> float(1.234)
1.234
>>> float('+1.23')
1.23
>>> float(' -12345n')
-12345.0
>>> float('1e-003')
0.001
>>> float('+1E6')
1000000.0
>>> float('-Infinity')
-inf
format()
>>> L = [['a', 123], ['by', 45.6], ['cow', 7.89]]
>>> for s, n in L:
... print(s, n)
...
a 123
by 45.6
cow 7.89
>>> for s, n in L:
... print(format(s, '^10') + '|' + format(n, '<.2f'))
...
a |123.00
by |45.60
cow |7.89 http://joequery.me/code/python-builtin-functions/#format
frozenset()
set
• mutable
• add()
• remove()
frozenset
• immutable: 생성된 이후에는
내용을 변경할 수 없음
getattr()
>>> class MyClass:
... x = 0
... y = 1
...
>>> myobj = MyClass()
>>> getattr(myobj, 'x')
0
globals()
>>> globals()
{'__name__': '__main__', '__builtins__': <module
'builtins' (built-in)>, '__loader__': <class '_frozen_
importlib.BuiltinImporter'>, '__spec__': None, '__
doc__': None, '__package__': None}
>>> balance = 200
>>> cost = 50
>>> globals()
{'__name__': '__main__', '__builtins__': <module
'builtins' (built-in)>, 'balance': 200, '__loader__': <
class '_frozen_importlib.BuiltinImporter'>, '__spe
c__': None, '__doc__': None, '__package__': Non
e, 'cost': 50}
>>> eval('balance - cost')
150
>>> mylocals = {'cost': 75}
>>> eval('balance - cost', mylocals)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'balance' is not defined
>>> eval('balance - cost', globals(), mylocals)
125
http://joequery.me/code/python-builtin-functions/#eval
hasattr()
>>> class MyClass:
... x = 0
... y = 1
...
>>> myobj = MyClass()
>>> hasattr(myobj, 'y')
True
>>> hasattr(myobj, 'z')
False
hash()
>>> hash('One little, two little, three little indians')
-7814896826006998464
>>> hash('indian')
-8497506485016990678
>>> hash('boy')
2674027540618413217
>>> hash('One little, two little, three little indians')
-7814896826006998464
>>> hash('indian')
-8497506485016990678
http://stackoverflow.com/questions/7646520/is-this-an-appropriate-use-of-pythons-built-in-hash-function
http://www.pythoncentral.io/hashing-strings-with-python/
help()
>>> help(eval)
Help on built-in function eval in module builtins:
eval(...)
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
hex()
>>> for n in range(20):
... print(hex(n))
...
0x0
0x1
0x2
0x3
0x4
0x5
0x6
0x7
0x8
0x9
0xa
0xb
0xc
0xd
0xe
0xf
0x10
0x11
0x12
0x13
id()
>>> a = 1
>>> b = 2
>>> L = [a, b]
>>> M = L
>>> id(L[0])
4297370688
>>> id(M[0])
4297370688
input()
>>> s = input('Type any string: ')
Type any string: Python
>>> print(s)
Python
int()
>>> n = int(input('Type any number: '))
Type any number: 3
>>> print(n * n)
9
isinstance()
>>> class Human:
... pass
...
>>> me = Human()
>>> isinstance(me, Human)
True
>>> class Robot:
... pass
...
>>> you = Robot()
>>> isinstance(you, Human)
False
>>> class Vehicle:
... pass
...
>>> class Car(Vehicle):
... pass
...
>>> mycar = Car()
>>> isinstance(mycar, Car)
True
>>> isinstance(mycar, Vehicle)
True
issubclass()
>>> class Vehicle:
... pass
...
>>> class Car(Vehicle):
... pass
...
>>> issubclass(Car, Vehicle)
True
iter()
>>> my_list = [5, 1, 6, 3]
>>> my_iter = iter(my_list)
>>> next(my_iter)
5
>>> next(my_iter)
1
>>> next(my_iter)
6
>>> next(my_iter)
3
len()
>>> len('Python')
6
>>> len('파이썬')
3
>>> len([2, 3, 6, 4, 5, 20])
6
list()
>>> list([1, 2, 3])
[1, 2, 3]
>>> list((1, 2, 3))
[1, 2, 3]
>>> list('XYZxyz')
['X', 'Y', 'Z', 'x', 'y', 'z']
locals()
>>> def foo(arg): # 함수 foo는 로컬 네임스페이스에 두 개의 변수 arg와 x를 가짐
... x = 1
... print(locals())
...
>>> foo(7) # locals는 이름/값 사전을 리턴
{'x': 1, 'arg': 7}
>>> foo('bar')
{'x': 1, 'arg': 'bar'}
http://www.diveintopython.net/html_processing/locals_and_globals.html
map()
for … in …
>>> M = list()
>>> for x in range(1, 6):
... M.append(x % 2)
...
>>> M
[1, 0, 1, 0, 1]
map()
>>> map(lambda x: x % 2, range(1, 6))
<map object at 0x101a67d30>
>>> list(_)
[1, 0, 1, 0, 1]
max()
>>> max(1234, 234, 34, 4)
1234
>>> max([3, 9, 27])
27
>>> max('return')
'u'
memoryview()
>>> ba = bytearray(b'abcdefgh')
>>> mv = memoryview(ba)
>>> mv[4:6]
<memory at 0x0000000002BB7CC8>
>>> mv[4:6].tobytes()
b'ef'
>>> mv[4:6] = b'ZA'
>>> ba
bytearray(b'abcdZAgh')
http://eli.thegreenplace.net/2011/11/28/less-copies-in-python-with-the-buffer-protocol-and-memoryviews
min()
>>> min(1234, 234, 34, 4)
4
>>> min('invest')
'e'
next()
>>> my_list = [5, 1, 6, 3]
>>> my_iter = iter(my_list)
>>> next(my_iter)
5
>>> next(my_iter)
1
>>> next(my_iter)
6
>>> next(my_iter)
3
object()
>>> obj = object()
>>> type(obj)
<class 'object'>
oct()
>>> for n in range(1, 21):
... print(str(n) + ': ' + oc
t(n))
...
1: 0o1
2: 0o2
3: 0o3
4: 0o4
5: 0o5
6: 0o6
7: 0o7
8: 0o10
9: 0o11
10: 0o12
11: 0o13
12: 0o14
13: 0o15
14: 0o16
15: 0o17
16: 0o20
17: 0o21
18: 0o22
19: 0o23
20: 0o24
open()
>>> with open("test.txt", "wt") as out_file:
... out_file.write("This Text is going to out filenLook at it
and see!")
...
50
>>> with open("test.txt", "rt") as in_file:
... text = in_file.read()
...
>>> print(text)
This Text is going to out file
Look at it and see!
https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/File_IO
ord()
>>> ord('A')
65
>>> ord('a')
97
>>> ord('1')
49
pow()
>>> pow(2, 5)
32
print()
>>> print('Python 3.4')
Python 3.4
>>> print('Python', '3.4')
Python 3.4
>>> print('Python', '3.4', sep='
')
Python 3.4
>>> print('Python', '3.4', sep='
_')
Python_3.4
>>> for x in range(3):
... print(x, end='n')
...
0
1
2
>>> for x in range(3):
... print(x, end='t')
...
0 1 2 >>>
property()
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x'
property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
>>> c = C()
>>> c.x = 10
>>> print(c.x)
10
>>> del c.x
>>> help(C)
Help on class C in module __main__:
class C(builtins.object)
| Methods defined here:
|
| __init__(self)
|
| -----------------------------------------------------------
-----------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| x
| I'm the 'x' property.
range()
>>> range(10)
range(0, 10)
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> tuple(range(5))
(0, 1, 2, 3, 4)
>>> for x in range(0, 10, 2):
... print(x)
...
0
2
4
6
8
>>> for y in range(10, 0, -1):
... print(y)
...
10
9
8
7
6
5
4
3
2
1
repr()
>>> repr('''Airbed
... Breakfast''')
"'AirbednBreakfast'"
>>> repr('김치')
"'김치'"
reversed()
>>> reversed([0, 1, 2, 3, 4])
<list_reverseiterator object at 0x101a67c50>
>>> list(reversed([0, 1, 2, 3, 4]))
[4, 3, 2, 1, 0]
round()
>>> round(3.1415)
3
>>> round(3.1415, 2)
3.14
set()
>>> A = set([n for n in range(2, 31, 2)])
>>> 4 in A
True
>>> len(A)
15
>>> A.add(32)
>>> A
{32, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26,
28, 30}
>>> {4, 8, 12}.issubset(A)
True
>>> {4, 8, 12} < A
True
>>> B = set([n for n in range(3, 31,
3)])
>>> C = A.intersection(B)
>>> C
{24, 18, 12, 6, 30}
>>> A.issuperset(C)
True
>>> sorted(C)
[6, 12, 18, 24, 30]
>>> D = A.union(B)
>>> D
{2, 3, 4, 6, 8, 9, 10, 12, 14, 15,
16, 18, 20, 21, 22, 24, 26, 27, 28,
30}
setattr()
>>> class Employee:
... def __init__(self, name, salary):
... self.name = name
... self.salary = salary
...
>>> j = Employee("John", "2000$")
>>> j.salary
'2000$'
>>> setattr(j, "salary", "3000$")
>>> j.salary
'3000$'
>>> setattr(j, "gender", "male")
>>> j.gender
'male'
slice()
>>> L = [0, 1, 2, 3, 4, 5, 6, 7,
8, 9]
>>> L[2:7]
[2, 3, 4, 5, 6]
>>> L[2:7:2]
[2, 4, 6]
>>> s = slice(2, 7)
>>> L[s]
[2, 3, 4, 5, 6]
>>> s = slice(2, 7, 2)
>>> L[s]
[2, 4, 6]
sorted()
>>> sorted([2, 3, 6, 4, 5, 20])
[2, 3, 4, 5, 6, 20]
staticmethod()
>>> class Util:
... @staticmethod
... def add(a, b):
... return a + b
...
>>> Util.add(2, 3)
5
http://pyengine.blogspot.kr/2011/08/staticmethod-vs-classmethod.html
str()
>>> str(1)
'1'
>>> str('a')
'a'
>>> str([1, 'a'])
"[1, 'a']"
>>> str(None)
'None'
sum()
>>> sum([3, 9, 27])
39
super()
class LoggingDict(dict):
def __setitem__(self, key, value):
logging.info('Settingto %r' % (key, value))
super().__setitem__(key, value)
https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
tuple()
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple((1, 2, 3))
(1, 2, 3)
>>> tuple('XYZxyz')
('X', 'Y', 'Z', 'x', 'y', 'z')
type()
>>> type(2)
<class 'int'>
>>> type('boy')
<class 'str'>
>>> type([2, 'boy'])
<class 'list'>
>>> type(None)
<class 'NoneType'>
>>> import calendar
>>> type(calendar)
<class 'module'>
>>> class MyClass:
... pass
...
>>> mc = MyClass()
>>> type(mc)
<class '__main__.MyClass'>
vars()
>>> class Employee:
... def __init__(self, name, salary):
... self.name = name
... self._salary = salary
...
...
>>> j = Employee("John", "2000$")
>>> vars(j)
{'name': 'John', '_salary': '2000$'}
zip()
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> list(zipped)
[]
__import__()
>>> from math import pi
>>> pi
3.141592653589793
>>> _temp = __import__('math', globals(), locals(), ['pi'], 0)
>>> pi = _temp.pi
>>> pi
3.141592653589793

More Related Content

PDF
Python fundamentals - basic | WeiYuan
PDF
Python Programming: Data Structure
PDF
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
PDF
Introducción a Elixir
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
PDF
Palestra sobre Collections com Python
KEY
Haskellで学ぶ関数型言語
PDF
Python dictionary : past, present, future
Python fundamentals - basic | WeiYuan
Python Programming: Data Structure
Goptuna Distributed Bayesian Optimization Framework at Go Conference 2019 Autumn
Introducción a Elixir
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
Palestra sobre Collections com Python
Haskellで学ぶ関数型言語
Python dictionary : past, present, future

What's hot (20)

PDF
Programmation fonctionnelle en JavaScript
PDF
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
KEY
Why Learn Python?
PDF
The Ring programming language version 1.5.2 book - Part 45 of 181
PDF
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
PDF
Using Scala Slick at FortyTwo
PPTX
Python GC
PDF
CoffeeScript
ODP
PDF
Observational Science With Python and a Webcam
PDF
The Ring programming language version 1.3 book - Part 83 of 88
PPTX
Benefits of Kotlin
PDF
Groovy collection api
PDF
Haskell in the Real World
PDF
Pytables
KEY
Code as data as code.
PDF
Rデバッグあれこれ
PDF
The Ring programming language version 1.10 book - Part 56 of 212
PDF
python高级内存管理
PDF
Visualization of Supervised Learning with {arules} + {arulesViz}
Programmation fonctionnelle en JavaScript
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
Why Learn Python?
The Ring programming language version 1.5.2 book - Part 45 of 181
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
Using Scala Slick at FortyTwo
Python GC
CoffeeScript
Observational Science With Python and a Webcam
The Ring programming language version 1.3 book - Part 83 of 88
Benefits of Kotlin
Groovy collection api
Haskell in the Real World
Pytables
Code as data as code.
Rデバッグあれこれ
The Ring programming language version 1.10 book - Part 56 of 212
python高级内存管理
Visualization of Supervised Learning with {arules} + {arulesViz}
Ad

Viewers also liked (20)

PPTX
Python 활용: 이미지 처리와 데이터 분석
PPTX
Python 표준 라이브러리
PPTX
Python 웹 프로그래밍
PPTX
Java와 Python의 만남: Jython과 Sikuli
PPTX
Python 생태계의 이해
PPTX
Python on Android
PPTX
Python 이해하기 20160815
PDF
Python quick guide1
PPTX
141103 최창원 파이썬 확장 프로그래밍
PDF
Character Encoding in python
PDF
병렬 프로그래밍
PDF
라즈베리파이 와 스카이로버 나노에 만남
PDF
20151219_(python_korea)_How_to_automate_webhacking.kr_with_Python_presentation
PPTX
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
PPTX
병렬 프로그래밍 패러다임
PPTX
파이썬 함수 이해하기
PDF
병렬프로그래밍과 Cuda
PDF
PyCon 12월 세미나 - 실전 파이썬 프로그래밍 책 홍보
PDF
Python Recipes for django girls seoul
PPTX
파이썬 병렬프로그래밍
Python 활용: 이미지 처리와 데이터 분석
Python 표준 라이브러리
Python 웹 프로그래밍
Java와 Python의 만남: Jython과 Sikuli
Python 생태계의 이해
Python on Android
Python 이해하기 20160815
Python quick guide1
141103 최창원 파이썬 확장 프로그래밍
Character Encoding in python
병렬 프로그래밍
라즈베리파이 와 스카이로버 나노에 만남
20151219_(python_korea)_How_to_automate_webhacking.kr_with_Python_presentation
Python의 계산성능 향상을 위해 Fortran, C, CUDA-C, OpenCL-C 코드들과 연동하기
병렬 프로그래밍 패러다임
파이썬 함수 이해하기
병렬프로그래밍과 Cuda
PyCon 12월 세미나 - 실전 파이썬 프로그래밍 책 홍보
Python Recipes for django girls seoul
파이썬 병렬프로그래밍
Ad

Similar to Python 내장 함수 (20)

PPTX
Super Advanced Python –act1
PDF
An overview of Python 2.7
PDF
A tour of Python
PDF
Refactoring to Macros with Clojure
PDF
PyCon 2010 SQLAlchemy tutorial
PDF
The Ring programming language version 1.7 book - Part 48 of 196
PDF
The Ring programming language version 1.5 book - Part 8 of 31
PDF
Beautiful python - PyLadies
PPTX
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
PDF
pa-pe-pi-po-pure Python Text Processing
PDF
Intro to Python
PDF
Functions in python
PPTX
Using-Python-Libraries.9485146.powerpoint.pptx
PDF
The Ring programming language version 1.9 book - Part 53 of 210
PDF
The Ring programming language version 1.6 book - Part 46 of 189
PDF
Javascript
PDF
Swift Sequences & Collections
PDF
The Ring programming language version 1.4.1 book - Part 13 of 31
PDF
The Ring programming language version 1.2 book - Part 32 of 84
Super Advanced Python –act1
An overview of Python 2.7
A tour of Python
Refactoring to Macros with Clojure
PyCon 2010 SQLAlchemy tutorial
The Ring programming language version 1.7 book - Part 48 of 196
The Ring programming language version 1.5 book - Part 8 of 31
Beautiful python - PyLadies
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
pa-pe-pi-po-pure Python Text Processing
Intro to Python
Functions in python
Using-Python-Libraries.9485146.powerpoint.pptx
The Ring programming language version 1.9 book - Part 53 of 210
The Ring programming language version 1.6 book - Part 46 of 189
Javascript
Swift Sequences & Collections
The Ring programming language version 1.4.1 book - Part 13 of 31
The Ring programming language version 1.2 book - Part 32 of 84

Recently uploaded (20)

PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Understanding Forklifts - TECH EHS Solution
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Nekopoi APK 2025 free lastest update
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Essential Infomation Tech presentation.pptx
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Understanding Forklifts - TECH EHS Solution
How to Migrate SBCGlobal Email to Yahoo Easily
Nekopoi APK 2025 free lastest update
Design an Analysis of Algorithms II-SECS-1021-03
Wondershare Filmora 15 Crack With Activation Key [2025
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Softaken Excel to vCard Converter Software.pdf
Odoo POS Development Services by CandidRoot Solutions
Which alternative to Crystal Reports is best for small or large businesses.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Essential Infomation Tech presentation.pptx
Reimagine Home Health with the Power of Agentic AI​
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
VVF-Customer-Presentation2025-Ver1.9.pptx

Python 내장 함수

  • 1. 파이썬 내장 함수 정보기술 시대에 유익한 파이썬 프로그래밍 – 제 6 강 (2) 동양미래대학교 2015.7 최용 <sk8er.choi@gmail.com>
  • 3. Python3 내장 함수 Built-in Functi ons abs() dict() help() min() setattr() all() dir() hex() next() slice() any() divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod() bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() delattr() hash() memoryview() set() https://docs.python.org/3/library/functions.html
  • 4. abs() >>> abs(-3) 3 >>> abs(-3.0) 3.0 >>> z = complex(1, 2) >>> abs(z) 2.23606797749979
  • 5. all() >>> all([True, True, True]) True >>> all([True, False, True]) False
  • 6. any() >>> any([True, False, True]) True >>> any((False, False, False)) False
  • 8. bin() >>> bin(1) '0b1' >>> bin(2) '0b10' >>> bin(3) '0b11' >>> bin(4) '0b100'
  • 9. bool() >>> bool(True) True >>> bool(2 < 3) True >>> bool(1) True >>> bool(3 % 2) True >>> bool(not None) True >>> bool(False) False >>> bool(2 > 3) False >>> bool(0) False >>> bool(4 % 2) False >>> bool(None) False >>> bool() False
  • 10. bytearray() >>> data = bytearray(b'Monty Python') >>> data[5] = 33 # mutable >>> data bytearray(b'Monty!Python') http://python3porting.com/problems.html#manipulating-binary-data http://dabeaz.blogspot.kr/2010/01/few-useful-bytearray-tricks.html
  • 11. bytes() >>> b'Python' b'Python' >>> type(b'Python') <class 'bytes'> >>> b'파이썬' File "<stdin>", line 1 SyntaxError: bytes can only contain ASCII literal characters. >>> bytes('Python', 'utf-8') b'Python' >>> bytes('파이썬', 'utf-8') b'xedx8cx8cxecx9dxb4xecx8dxac'
  • 12. callable() >>> def sum(x, y): ... return x + y ... >>> callable(sum) True >>> x = 10 >>> callable(x) False >>> class MyClass: ... pass ... >>> callable(MyClass) True >>> obj = MyClass() >>> callable(obj) False http://joequery.me/code/python-builtin-functions/#callable
  • 14. classmethod() >>> class Pizza: ... radius = 42 ... @classmethod ... def get_radius(cls): ... return cls.radius ... >>> Pizza.get_radius() 42 https://julien.danjou.info/blog/2013/guide-python-static-class-abstract-methods
  • 15. compile() >>> codeobj = compile('x = 2nprint("X is " + str(x))', # source ... 'fakemodule', # file name ... 'exec') # mode >>> exec(codeobj) X is 2 http://stackoverflow.com/questions/22443939/python-built-in-function-compile-what-is-it-used-for
  • 16. complex() >>> x = complex("4+2j") >>> x (4+2j) >>> y = complex("4-5j") >>> y (4-5j) >>> x+y (8-3j) >>> x*y (26-12j) >>> complex("4") (4+0j) http://joequery.me/code/python-builtin-functions/#complex
  • 17. delattr() >>> class Employee: ... def __init__(self, name, salary): ... self.name = name ... self.salary = salary ... >>> j = Employee("John", "2000$") >>> j.salary '2000$' >>> delattr(j, "salary") >>> hasattr(j, "salary") False
  • 18. dict() >>> dict() {} >>> dict( [[1, 'a'], [2, 'b'], [3, 'c']] ) {1: 'a', 2: 'b', 3: 'c'} >>> dict( ((1, 'a'), (2, 'b'), (3, 'c')) ) {1: 'a', 2: 'b', 3: 'c'}
  • 19. dir() >>> class Shape: ... def __dir__(self): ... return ['area', 'perimeter', 'location'] ... >>> s = Shape() >>> dir(s) ['area', 'location', 'perimeter'] >>> import struct >>> dir(struct) ['Struct', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pack age__', '__spec__', '_clearcache', 'calcsize', 'error', 'iter_unpack', 'pack', 'pack_into', 'unpack', 'unpack_ from']
  • 20. divmod() >>> divmod(7, 3) (2, 1) >>> divmod(8.4, 4.2) (2.0, 0.0) >>> divmod(8.5, 4.2) (2.0, 0.09999999999999964)
  • 21. enumerate() >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
  • 22. eval() >>> x = 1 >>> eval('x + 1') 2 >>> y = eval('x + 2') >>> y 3 >>> a = 10 >>> b = 5 >>> D = {'a': 2, 'b': 3} >>> eval('a + b') 15 >>> eval('a + b', D) 5
  • 23. exec() >>> a = 3 >>> exec('b = 2') # eval()과 달리, 값을 리턴하지 않음 >>> exec('c = a + b') >>> c 5
  • 24. filter() >>> N = range(1, 11) >>> Even = list() >>> for n in N: ... if n % 2 == 0: ... Even.append(n) ... >>> Even [2, 4, 6, 8, 10] >>> Odd = list(filter(lambda x: x % 2, N)) >>> Odd [1, 3, 5, 7, 9]
  • 25. float() >>> float(1) 1.0 >>> float(1.234) 1.234 >>> float('+1.23') 1.23 >>> float(' -12345n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf
  • 26. format() >>> L = [['a', 123], ['by', 45.6], ['cow', 7.89]] >>> for s, n in L: ... print(s, n) ... a 123 by 45.6 cow 7.89 >>> for s, n in L: ... print(format(s, '^10') + '|' + format(n, '<.2f')) ... a |123.00 by |45.60 cow |7.89 http://joequery.me/code/python-builtin-functions/#format
  • 27. frozenset() set • mutable • add() • remove() frozenset • immutable: 생성된 이후에는 내용을 변경할 수 없음
  • 28. getattr() >>> class MyClass: ... x = 0 ... y = 1 ... >>> myobj = MyClass() >>> getattr(myobj, 'x') 0
  • 29. globals() >>> globals() {'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__loader__': <class '_frozen_ importlib.BuiltinImporter'>, '__spec__': None, '__ doc__': None, '__package__': None} >>> balance = 200 >>> cost = 50 >>> globals() {'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, 'balance': 200, '__loader__': < class '_frozen_importlib.BuiltinImporter'>, '__spe c__': None, '__doc__': None, '__package__': Non e, 'cost': 50} >>> eval('balance - cost') 150 >>> mylocals = {'cost': 75} >>> eval('balance - cost', mylocals) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'balance' is not defined >>> eval('balance - cost', globals(), mylocals) 125 http://joequery.me/code/python-builtin-functions/#eval
  • 30. hasattr() >>> class MyClass: ... x = 0 ... y = 1 ... >>> myobj = MyClass() >>> hasattr(myobj, 'y') True >>> hasattr(myobj, 'z') False
  • 31. hash() >>> hash('One little, two little, three little indians') -7814896826006998464 >>> hash('indian') -8497506485016990678 >>> hash('boy') 2674027540618413217 >>> hash('One little, two little, three little indians') -7814896826006998464 >>> hash('indian') -8497506485016990678 http://stackoverflow.com/questions/7646520/is-this-an-appropriate-use-of-pythons-built-in-hash-function http://www.pythoncentral.io/hashing-strings-with-python/
  • 32. help() >>> help(eval) Help on built-in function eval in module builtins: eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it.
  • 33. hex() >>> for n in range(20): ... print(hex(n)) ... 0x0 0x1 0x2 0x3 0x4 0x5 0x6 0x7 0x8 0x9 0xa 0xb 0xc 0xd 0xe 0xf 0x10 0x11 0x12 0x13
  • 34. id() >>> a = 1 >>> b = 2 >>> L = [a, b] >>> M = L >>> id(L[0]) 4297370688 >>> id(M[0]) 4297370688
  • 35. input() >>> s = input('Type any string: ') Type any string: Python >>> print(s) Python
  • 36. int() >>> n = int(input('Type any number: ')) Type any number: 3 >>> print(n * n) 9
  • 37. isinstance() >>> class Human: ... pass ... >>> me = Human() >>> isinstance(me, Human) True >>> class Robot: ... pass ... >>> you = Robot() >>> isinstance(you, Human) False >>> class Vehicle: ... pass ... >>> class Car(Vehicle): ... pass ... >>> mycar = Car() >>> isinstance(mycar, Car) True >>> isinstance(mycar, Vehicle) True
  • 38. issubclass() >>> class Vehicle: ... pass ... >>> class Car(Vehicle): ... pass ... >>> issubclass(Car, Vehicle) True
  • 39. iter() >>> my_list = [5, 1, 6, 3] >>> my_iter = iter(my_list) >>> next(my_iter) 5 >>> next(my_iter) 1 >>> next(my_iter) 6 >>> next(my_iter) 3
  • 41. list() >>> list([1, 2, 3]) [1, 2, 3] >>> list((1, 2, 3)) [1, 2, 3] >>> list('XYZxyz') ['X', 'Y', 'Z', 'x', 'y', 'z']
  • 42. locals() >>> def foo(arg): # 함수 foo는 로컬 네임스페이스에 두 개의 변수 arg와 x를 가짐 ... x = 1 ... print(locals()) ... >>> foo(7) # locals는 이름/값 사전을 리턴 {'x': 1, 'arg': 7} >>> foo('bar') {'x': 1, 'arg': 'bar'} http://www.diveintopython.net/html_processing/locals_and_globals.html
  • 43. map() for … in … >>> M = list() >>> for x in range(1, 6): ... M.append(x % 2) ... >>> M [1, 0, 1, 0, 1] map() >>> map(lambda x: x % 2, range(1, 6)) <map object at 0x101a67d30> >>> list(_) [1, 0, 1, 0, 1]
  • 44. max() >>> max(1234, 234, 34, 4) 1234 >>> max([3, 9, 27]) 27 >>> max('return') 'u'
  • 45. memoryview() >>> ba = bytearray(b'abcdefgh') >>> mv = memoryview(ba) >>> mv[4:6] <memory at 0x0000000002BB7CC8> >>> mv[4:6].tobytes() b'ef' >>> mv[4:6] = b'ZA' >>> ba bytearray(b'abcdZAgh') http://eli.thegreenplace.net/2011/11/28/less-copies-in-python-with-the-buffer-protocol-and-memoryviews
  • 46. min() >>> min(1234, 234, 34, 4) 4 >>> min('invest') 'e'
  • 47. next() >>> my_list = [5, 1, 6, 3] >>> my_iter = iter(my_list) >>> next(my_iter) 5 >>> next(my_iter) 1 >>> next(my_iter) 6 >>> next(my_iter) 3
  • 48. object() >>> obj = object() >>> type(obj) <class 'object'>
  • 49. oct() >>> for n in range(1, 21): ... print(str(n) + ': ' + oc t(n)) ... 1: 0o1 2: 0o2 3: 0o3 4: 0o4 5: 0o5 6: 0o6 7: 0o7 8: 0o10 9: 0o11 10: 0o12 11: 0o13 12: 0o14 13: 0o15 14: 0o16 15: 0o17 16: 0o20 17: 0o21 18: 0o22 19: 0o23 20: 0o24
  • 50. open() >>> with open("test.txt", "wt") as out_file: ... out_file.write("This Text is going to out filenLook at it and see!") ... 50 >>> with open("test.txt", "rt") as in_file: ... text = in_file.read() ... >>> print(text) This Text is going to out file Look at it and see! https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3/File_IO
  • 53. print() >>> print('Python 3.4') Python 3.4 >>> print('Python', '3.4') Python 3.4 >>> print('Python', '3.4', sep=' ') Python 3.4 >>> print('Python', '3.4', sep=' _') Python_3.4 >>> for x in range(3): ... print(x, end='n') ... 0 1 2 >>> for x in range(3): ... print(x, end='t') ... 0 1 2 >>>
  • 54. property() class C: def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x >>> c = C() >>> c.x = 10 >>> print(c.x) 10 >>> del c.x >>> help(C) Help on class C in module __main__: class C(builtins.object) | Methods defined here: | | __init__(self) | | ----------------------------------------------------------- ----------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | x | I'm the 'x' property.
  • 55. range() >>> range(10) range(0, 10) >>> list(range(5)) [0, 1, 2, 3, 4] >>> tuple(range(5)) (0, 1, 2, 3, 4) >>> for x in range(0, 10, 2): ... print(x) ... 0 2 4 6 8 >>> for y in range(10, 0, -1): ... print(y) ... 10 9 8 7 6 5 4 3 2 1
  • 57. reversed() >>> reversed([0, 1, 2, 3, 4]) <list_reverseiterator object at 0x101a67c50> >>> list(reversed([0, 1, 2, 3, 4])) [4, 3, 2, 1, 0]
  • 59. set() >>> A = set([n for n in range(2, 31, 2)]) >>> 4 in A True >>> len(A) 15 >>> A.add(32) >>> A {32, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30} >>> {4, 8, 12}.issubset(A) True >>> {4, 8, 12} < A True >>> B = set([n for n in range(3, 31, 3)]) >>> C = A.intersection(B) >>> C {24, 18, 12, 6, 30} >>> A.issuperset(C) True >>> sorted(C) [6, 12, 18, 24, 30] >>> D = A.union(B) >>> D {2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 26, 27, 28, 30}
  • 60. setattr() >>> class Employee: ... def __init__(self, name, salary): ... self.name = name ... self.salary = salary ... >>> j = Employee("John", "2000$") >>> j.salary '2000$' >>> setattr(j, "salary", "3000$") >>> j.salary '3000$' >>> setattr(j, "gender", "male") >>> j.gender 'male'
  • 61. slice() >>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> L[2:7] [2, 3, 4, 5, 6] >>> L[2:7:2] [2, 4, 6] >>> s = slice(2, 7) >>> L[s] [2, 3, 4, 5, 6] >>> s = slice(2, 7, 2) >>> L[s] [2, 4, 6]
  • 62. sorted() >>> sorted([2, 3, 6, 4, 5, 20]) [2, 3, 4, 5, 6, 20]
  • 63. staticmethod() >>> class Util: ... @staticmethod ... def add(a, b): ... return a + b ... >>> Util.add(2, 3) 5 http://pyengine.blogspot.kr/2011/08/staticmethod-vs-classmethod.html
  • 64. str() >>> str(1) '1' >>> str('a') 'a' >>> str([1, 'a']) "[1, 'a']" >>> str(None) 'None'
  • 66. super() class LoggingDict(dict): def __setitem__(self, key, value): logging.info('Settingto %r' % (key, value)) super().__setitem__(key, value) https://rhettinger.wordpress.com/2011/05/26/super-considered-super/
  • 67. tuple() >>> tuple([1, 2, 3]) (1, 2, 3) >>> tuple((1, 2, 3)) (1, 2, 3) >>> tuple('XYZxyz') ('X', 'Y', 'Z', 'x', 'y', 'z')
  • 68. type() >>> type(2) <class 'int'> >>> type('boy') <class 'str'> >>> type([2, 'boy']) <class 'list'> >>> type(None) <class 'NoneType'> >>> import calendar >>> type(calendar) <class 'module'> >>> class MyClass: ... pass ... >>> mc = MyClass() >>> type(mc) <class '__main__.MyClass'>
  • 69. vars() >>> class Employee: ... def __init__(self, name, salary): ... self.name = name ... self._salary = salary ... ... >>> j = Employee("John", "2000$") >>> vars(j) {'name': 'John', '_salary': '2000$'}
  • 70. zip() >>> x = [1, 2, 3] >>> y = [4, 5, 6] >>> zipped = zip(x, y) >>> list(zipped) [(1, 4), (2, 5), (3, 6)] >>> list(zipped) []
  • 71. __import__() >>> from math import pi >>> pi 3.141592653589793 >>> _temp = __import__('math', globals(), locals(), ['pi'], 0) >>> pi = _temp.pi >>> pi 3.141592653589793

Editor's Notes

  • #30: Return the dictionary containing the current scope's global variables.
  • #31: hasattr(...) hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching AttributeError.)
  • #32: hash(...) hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely.
  • #35: id(...) id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)
  • #43: locals(...) locals() -> dictionary Update and return a dictionary containing the current scope's local variables.
  • #46: class memoryview(object) | memoryview(object) | | Create a new memoryview object which references the given object.
  • #72: Note  This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().