Uploaded by gmlfks5883

컴퓨터과학적인식과문제해결 강의10b 파이썬 (Python) IV

advertisement
컴퓨터과학적 인식과 문제해결
강의 10b
• 파이썬 (Python) IV
이화여자대학교
2020년 1학기
교과목명
학수번호-분반
컴퓨터과학적 인식과 문제해결
11205-01
개설전공
엘텍공과대학
학점/시간
3/3
수업시간/강의실
담당교원
E-mail/전화
면담시간/장소
월2(9:30~10:45), 목3(11:00~12:15) 원격 수업
이재현
jaylee351@gmail.com / 010-9986-6502
(강의 내용 문의는 사이버캠퍼스 메시지로 할 것)
강의 전 후
https://www.python.org/downloads/
강의 10b: 파이썬 (Python) IV
• Python Escape Codes
• Python Standard Library
1. Python Escape Codes
The back-slash character enclosed within quotes won’t be
displayed but instead indicates that a formatting (escape)
code will follow the slash: back-slash는 \임
Escape sequence
Description
\a
Alarm. Causes the program to beep.
\n
Newline. Moves the cursor to beginning of the next line.
\t
Tab. Moves the cursor forward one tab stop.
\'
Single quote. Prints a single quote.
\"
Double quote. Prints a double quote.
\\
Backslash. Prints one backslash.
1. Python Escape Codes
• Escape Code 사례
a=[1,2,3,4,5]
print(‘\n ',a)
print('\a',a)
print('\t',a)
print('\'')
print('\"')
print('\\')
>>>
RESTART:
C:/Users/Jay/AppData/Local/Programs/Python/Python3
7-32/escape codes.py
[1, 2, 3, 4, 5]
● [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
'
"
\
>>>
2. Python Standard Library
• Built-in Functions in Python: 68개
• Python List Methods: 28개
• Python String Methods: 68개
• Python Dictionary Methods: 26개
▪ https://www.programiz.com/pythonprogramming/methods/dictionary
• Python Set Methods: 33개
▪ https://www.programiz.com/python-programming/methods/set
• Python Tuple Methods: 19개
▪ https://www.programiz.com/python-programming/methods/tuple
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions: 항상 사용 가능한 기능 68개
abs()
returns absolute value of a number
all()
returns true when all elements in iterable is true
any()
Checks if any Element of an Iterable is True
ascii()
Returns String Containing Printable Representation
bin()
converts integer to binary string
bool()
Converts a Value to Boolean
bytearray()
returns array of given byte size
bytes()
returns immutable bytes object
callable()
Checks if the Object is Callable
chr()
Returns a Character (a string) from an Integer
classmethod()
returns class method for given function
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions: 항상 사용 가능한 기능 68개
compile()
Returns a Python code object
complex()
Creates a Complex Number
delattr()
Deletes Attribute From the Object
dict()
Creates a Dictionary
dir()
Tries to Return Attributes of Object
divmod()
Returns a Tuple of Quotient and Remainder
enumerate()
Returns an Enumerate Object
eval()
Runs Python Code Within Program
exec()
Executes Dynamically Created Program
filter()
constructs iterator from elements which are true
float()
returns floating point number from number, string
format()
returns formatted representation of a value
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions: 항상 사용 가능한 기능 68개
frozenset()
returns immutable frozenset object
getattr()
returns value of named attribute of an object
globals()
returns dictionary of current global symbol table
hasattr()
returns whether object has named attribute
hash()
returns hash value of an object
help()
Invokes the built-in Help System
hex()
Converts to Integer to Hexadecimal
id()
Returns Identify of an Object
input()
reads and returns a line of string
int()
returns integer from a number or string
isinstance()
Checks if a Object is an Instance of Class
issubclass()
Checks if a Object is Subclass of a Class
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions: 항상 사용 가능한 기능 68개
iter()
returns iterator for an object
len()
Returns Length of an Object
list()
creates list in Python
locals()
Returns dictionary of a current local symbol table
map()
Applies Function and Returns a List
max()
returns largest element
memoryview()
returns memory view of an argument
min()
returns smallest element
next()
Retrieves Next Element from Iterator
object()
Creates a Featureless Object
oct()
converts integer to octal
open()
Returns a File object
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions: 항상 사용 가능한 기능 68개
ord()
returns Unicode code point for Unicode character
pow()
returns x to the power of y
print()
Prints the Given Object
property()
returns a property attribute
range()
return sequence of integers between start and stop
repr()
returns printable representation of an object
reversed()
returns reversed iterator of a sequence
round()
rounds a floating point number to ndigits places.
set()
returns a Python set
setattr()
sets value of an attribute of object
slice()
creates a slice object specified by range()
sorted()
returns sorted list from a given iterable
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions: 항상 사용 가능한 기능 68개
staticmethod()
creates static method from a function
str()
returns informal representation of an object
sum()
Add items of an Iterable
super()
Allow you to Refer Parent Class by super
tuple()
Creates a Tuple
type()
Returns Type of an Object
vars()
Returns __dict__ attribute of a class
zip()
Returns an Iterator of Tuples
__import__()
Advanced Function Called by import
https://www.programiz.com/python-programming/methods/built-in
2. Python Standard Library
• Built-in Functions 사례
>>> bin(10)
‘0b1010’
>>> float(5)
5.0
>>> hex(15)
‘0xf’
>>> a=input(‘Enter a real numb’)
3.3
>>> int(a)
3
2. Python Standard Library
• Built-in Functions 사례
>>> a=list(range(1,5)) + list(range(10,25,3))
>>> print(a)
[1,2,3,4,10,13,16,19,22]
len(a)
9
>>> max(a)
22
>>> min(a)
1
>>> oct(25)
‘0o31’
2. Python Standard Library
• Built-in Functions 사례
>>> a=[5,3,8,2,9,4,7,1,0,6]
>>> sorted(a)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(a)
45
>>> round(3.33)
3
>>> str(3)
‘3’
>>> type(a)
<class ‘list’>
2. Python Standard Library
• Built-in Functions 사례
>>> n=123456789
>>> format(n,’,’)
#천 단위 쉼표
‘123,456,789’
>>> n=123456789.12345
>>> format(n,’.2f’)
#소수점 자릿수
'123456789.12’
>>> n=12345
>>> format(n,’10’)
‘
#전체 자릿수
12345’
>>> format(n,’10d’)
‘
12345’
파이썬으로 배우는 컴퓨팅사고, 김완섭, Infinity Books, 2019
2. Python Standard Library
• Built-in Functions 사례
>>> n=12345
>>> format(n,’<10’)
'12345
#좌우정렬
‘
>>> format(n,’>10’)
'
12345’
>>> n=12345.12345
>>> format(n, ‘>15,.2f’)
'
#복합적 포맷 설정
12,345.12’
>>> n=12345.12345
>>> format(n, ‘e’)
'1.234512e+04'
파이썬으로 배우는 컴퓨팅사고, 김완섭, Infinity Books, 2019
#지수 형태로 출력
2. Python Standard Library
• List Methods 28개
append()
데이터를 리스트 끝에 추가한다
extend()
리스트를 추가한다.
insert()
데이터를 지정한 위치에 삽입한다
remove()
리스트의 지정한 값 하나를 삭제한다
index()
요소를 검색한다
count()
요소의 개소를 알아낸다
pop()
리스트의 지정한 값하나를 읽어내고 삭제한다.
reverse()
리스트의 순서를 바꾼다
sort()
리스트를 정렬한다.
copy()
Returns Shallow Copy of a List
clear()
Removes all Items from the List
any()
Checks if any Element of an Iterable is True
https://www.programiz.com/python-programming/methods/list
2. Python Standard Library
• List Methods 28개
all()
returns true when all elements in iterable is true
ascii()
Returns String Containing Printable Representation
bool()
Converts a Value to Boolean
enumerate()
Returns an Enumerate Object
filter()
constructs iterator from elements which are true
iter()
returns iterator for an object
list()
creates list in Python
len()
Returns Length of an Object
max()
returns largest element
min()
returns smallest element
map()
Applies Function and Returns a List
reversed()
returns reversed iterator of a sequence
https://www.programiz.com/python-programming/methods/list
2. Python Standard Library
• List Methods 28개
slice()
creates a slice object specified by range()
sorted()
returns sorted list from a given iterable
sum()
Add items of an Iterable
zip()
Returns an Iterator of Tuples
https://www.programiz.com/python-programming/methods/list
2. Python Standard Library
• List Methods 사례
>>> a=[5,3,8,2,9,4,7,1,0,6]
>>> a.append(99)
>>> a
[5, 3, 8, 2, 9, 4, 7, 1, 0, 6, 99]
>>> a.insert(3,55)
>>> a
[5, 3, 8, 55, 2, 9, 4, 7, 1, 0, 6, 99]
>>> a.index(0)
9
>>> a.count(5)
1
소프트웨어와 컴퓨팅 사고, 김대수, 생능출판사, 2016
>>> a.sort()
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8,
>>> a.reverse()
>>> a
[99, 55, 9, 8, 7, 6, 5, 4,
>>> a.remove(0)
[99, 55, 9, 8, 7, 6, 5, 4,
>>> a.pop()
1
>>> a
[99, 55, 9, 8, 7, 6, 5, 4,
>>> a.extend([11,22])
>>> a
[99, 55, 9, 8, 7, 6, 5, 4,
9, 55, 99]
3, 2, 1, 0]
3, 2, 1]
3, 2]
3, 2, 11, 22]
2. Python Standard Library
• List Methods 사례
>>> b=[‘p’, ‘q’, ‘r’, ‘s’, ‘u’, ‘y’]
>>> b.append(‘t’)
>>> b
['p', 'q', 'r', 's', 'u', 'y', 't']
>>> b.insert(3,’h’)
>>> b
['p', 'q', 'r', 'h', 's', 'u', 'y', 't']
>>> b.index(‘r’)
2
>>> b.count(‘u’)
1
소프트웨어와 컴퓨팅 사고, 김대수, 생능출판사, 2016
>>> b.sort()
>>> b
['h', 'p', 'q', 'r', 's', 't', 'u', 'y']
>>> b.reverse()
>>> b
['y', 'u', 't', 's', 'r', 'q', 'p', 'h']
>>> b.remove(‘p’)
['y', 'u', 't', 's', 'r', 'q', 'h']
>>> b.pop()
‘h’
>>> b
['y', 'u', 't', 's', 'r', 'q']
>>> b.extend([‘hello’,’good’])
>>> b
['y', 'u', 't', 's', 'r', 'q', 'hello', 'good']
2. Python Standard Library
• String Methods 68개
capitalize()
Converts first character to Capital Letter
center()
Pads string with specified character
casefold()
converts to casefolded strings
count()
returns occurrences of substring in string
endswith()
Checks if String Ends with the Specified Suffix
expandtabs()
Replaces Tab character With Spaces
encode()
returns encoded string of given string
find()
Returns the index of first occurrence of substring
format()
formats string into nicer output
index()
Returns Index of Substring
isalnum()
Checks Alphanumeric Character
isalpha()
Checks if All Characters are Alphabets
https://www.programiz.com/python-programming/methods/string
2. Python Standard Library
• String Methods 68개
isdecimal()
Checks Decimal Characters
isdigit()
Checks Digit Characters
isidentifier()
Checks for Valid Identifier
islower()
Checks if all Alphabets in a String are Lowercase
isnumeric()
Checks Numeric Characters
isprintable()
Checks Printable Character
isspace()
Checks Whitespace Characters
istitle()
Checks for Titlecased String
isupper()
returns if all characters are uppercase characters
join()
Returns a Concatenated String
ljust()
returns left-justified string of given width
rjust()
returns right-justified string of given width
https://www.programiz.com/python-programming/methods/string
2. Python Standard Library
• String Methods 68개
lower()
returns lowercased string
upper()
returns uppercased string
swapcase()
swap uppercase characters to lowercase; vice versa
lstrip()
Removes Leading Characters
rstrip()
Removes Trailing Characters
strip()
Removes Both Leading and Trailing Characters
partition()
Returns a Tuple
maketrans()
returns a translation table
rpartition()
Returns a Tuple
translate()
returns mapped charactered string
replace()
Replaces Substring Inside
rfind()
Returns the Highest Index of Substring
https://www.programiz.com/python-programming/methods/string
2. Python Standard Library
• String Methods 68개
rindex()
Returns Highest Index of Substring
split()
Splits String from Left
rsplit()
Splits String From Right
splitlines()
Splits String at Line Boundaries
startswith()
Checks if String Starts with the Specified String
title()
Returns a Title Cased String
zfill()
Returns a Copy of The String Padded With Zeros
format_map()
Formats the String Using Dictionary
any()
Checks if any Element of an Iterable is True
all()
returns true when all elements in iterable is true
ascii()
Returns String Containing Printable Representation
bool()
Converts a Value to Boolean
https://www.programiz.com/python-programming/methods/string
2. Python Standard Library
• String Methods 68개
bytearray()
returns array of given byte size
bytes()
returns immutable bytes object
compile()
Returns a Python code object
complex()
Creates a Complex Number
enumerate()
Returns an Enumerate Object
filter()
constructs iterator from elements which are true
float()
returns floating point number from number, string
input()
reads and returns a line of string
int()
returns integer from a number or string
iter()
returns iterator for an object
len()
Returns Length of an Object
max()
returns largest element
https://www.programiz.com/python-programming/methods/string
2. Python Standard Library
• String Methods 68개
min()
returns smallest element
map()
Applies Function and Returns a List
ord()
returns Unicode code point for Unicode character
reversed()
returns reversed iterator of a sequence
slice()
creates a slice object specified by range()
sorted()
returns sorted list from a given iterable
sum()
Add items of an Iterable
zip()
Returns an Iterator of Tuples
https://www.programiz.com/python-programming/methods/string
2. Python Standard Library
• String Methods 사례
>>> a=‘I love Python’
>>> b=a.count(‘o’)
>>> print(b)
2
>>> c=a.find(‘Py’)
7
>>> a.index(‘o’)
3
>>> a=[2,6,3,8,4,9,1,0]
>>> sorted(a)
[0, 1, 2, 3, 4, 6, 8, 9]
2. Python Standard Library
• String Methods 사례
>>> a=‘I love Python’
>>> b=a.upper()
>>> c=a.lower()
>>> print(b)
I LOVE PYTHON
>>> print(c)
i love python
>>> print(a.replace(‘love’,’LIKE’))
I LIKE Python
2. Python Standard Library
• Math Functions
List of Functions in Python Math Module
Function Description
ldexp(x, i) Returns x * (2**i)
modf(x)
Returns the fractional and integer parts of x
trunc(x)
Returns the truncated integer value of x
exp(x)
Returns e**x
expm1(x) Returns e**x - 1
log(x[, base]) Returns the logarithm of x to the base (defaults to e)
log1p(x)
Returns the natural logarithm of 1+x
log2(x)
Returns the base-2 logarithm of x
log10(x) Returns the base-10 logarithm of x
pow(x, y) Returns x raised to the power y
sqrt(x)
Returns the square root of x
https://docs.python.org/3/library/
2. Python Standard Library
• Math Functions
List of Functions in Python Math Module
Function
Description
ceil(x)
Returns the smallest integer greater than or equal to x.
copysign(x, y) Returns x with the sign of y
fabs(x)
Returns the absolute value of x
factorial(x) Returns the factorial of x
floor(x)
Returns the largest integer less than or equal to x
fmod(x, y) Returns the remainder when x is divided by y
frexp(x)
Returns the mantissa and exponent of x as the pair (m, e)
Returns an accurate floating point sum of values in the
fsum(iterable)
iterable
Returns True if x is neither an infinity nor a NaN
isfinite(x)
(Not a Number)
isinf(x)
Returns True if x is a positive or negative infinity
isnan(x)
Returns True if x is a NaN
https://docs.python.org/3/library/
2. Python Standard Library
• Math Functions
Function
acos(x)
asin(x)
atan(x)
atan2(y, x)
cos(x)
hypot(x, y)
sin(x)
tan(x)
degrees(x)
radians(x)
acosh(x)
List of Functions in Python Math Module
Description
Returns the arc cosine of x
Returns the arc sine of x
Returns the arc tangent of x
Returns atan(y / x)
Returns the cosine of x
Returns the Euclidean norm, sqrt(x*x + y*y)
Returns the sine of x
Returns the tangent of x
Converts angle x from radians to degrees
Converts angle x from degrees to radians
Returns the inverse hyperbolic cosine of x
https://docs.python.org/3/library/
2. Python Standard Library
• Math Functions
Function
asinh(x)
atanh(x)
cosh(x)
sinh(x)
tanh(x)
erf(x)
erfc(x)
gamma(x)
lgamma(x)
pi
e
List of Functions in Python Math Module
Description
Returns the inverse hyperbolic sine of x
Returns the inverse hyperbolic tangent of x
Returns the hyperbolic cosine of x
Returns the hyperbolic cosine of x
Returns the hyperbolic tangent of x
Returns the error function at x
Returns the complementary error function at x
Returns the Gamma function at x
Returns the natural logarithm of the absolute value of the
Gamma function at x
Mathematical constant, the ratio of circumference of a circle
to it's diameter (3.14159...)
mathematical constant e (2.71828...)
https://docs.python.org/3/library/
2. Python Standard Library
• Math Functions 사례
>>> import math
>>> math.sin(math.radians(30))
>>> math.log10(1000)
0.49999999999999994
3.0
>>> math.cos(math.radians(60))
>>> math.pow(8, 2)
64.0
>>> print(math.sqrt(2))
1.4142135623730951
0.5000000000000001
>>> math.tan(math.radians(45))
0.9999999999999999
>>> math.sin(math.pi/6)
0.49999999999999994
>>> math.factorial(10)
>>> math.cos(math.pi/3)
3628800
0.5000000000000001
>>> math.tan(math.pi/4)
0.9999999999999999
Download