CH_2 Python Data Types
Keywords:
Expressions, Variables, Data Types in Python,
Objects and class, Module library in Python
Contents
2.1 Expressions, Variables, and Assignments
2.2 Strings
2.3 Lists
2.4 Objects and Classes
2.5 Python Standard Library
Chapter Summary
2
Expressions, Variables, and Assignments
At the Python IDLE interactive shell >>> 3+7
10
prompt >>>, type algebraic expressions, then
>>> 3*2
press “enter” key. 6
You may use python as a calculator! >>> 5/2
표현식을 입력하고 “enter“ key를 입력하면 평가 2.5 # not an int but float type
결과를 보여줌 >>> 4/2
2.0 # not 2 but 2.0
Int + int returns int
>>> 2*3+1
Int * int returns int 7 # evaluates (2 * 3) then 5+1
Int / int returns float type >>> (3 + 1) * 3
Int, float type
12 # use parenthesis to indicate an
# evaluation order
“int” means an integer number, 정수형 >>> 4.321 / 3 + 10
“float” means a real number in algebra, or 11.440333333333333
floating point number in CS (Computer Science) >>> 4.321 / (3 + 10)
실수형 0.3323846153846154
3
Expressions, Variables, and Assignments
Multiple operation
연산 순서 중요!!!
연산(자) 우선 순위 (precedence rule)
좌에서 우측 순 평가 (Left-to-right evaluation)
Expressions
Mathematic expressions, Logic expressions etc…
A set of statements to instruct operations or tasks.
Operations, operators and operands
To do an operation, there are at least one operator and operand(s)
In the expression “3 + 7”
One operator “+“ and two operands “3”, “7”
위에서와 같이 보통 연산자는 두개의 피연산자를 취한다. Binary operator 라 한다.
하지만 피연산자를 하나만 취하는 단항 연산자 (Unary operator)도 존재한다.
4
Expressions, Variables, and Assignments
#the exponentiation operator **: Several other algebraic operators
>>> 2**3 exponentiation operator **
8 x ** y xy
>>> 2**4 Integer quotient and the remainder
16 operator
#operators // and % 14 // 3 4
A.k.a “integer division”
>>> 14 // 3
14 % 3 2
4 A.k.a. “modulo”
#14/3 returns 4.666 so integer part of this is 4
>>> 14 % 3
2 # 2 is the remainder when 14 divided by 3 Functions
>>> abs(-4) abs(x) returns absolute value of x
>>> min(6, -2)
4 min( )
-2
>>> abs(4) max( )
>>> max(6, -2)
4 Above are Python built-in functions
6
>>> abs(-3.2)
>>> min(2, -4, 6, -2)
3.2
-4
>>> max(12, 26.5, 3.5)
5
26.5
Practice Problem
다음 문장에 해당되는 Python 대수 표현식을 작성하라
처음 5개의 양의 정수의 합
The average age of Sara (age 23), Mark (age 19), and Fatima (age 31)
The number of times 73 goes into 403
The remainder when 403 is divided by 73
2 to the 10th power
The absolute value of the difference between Sara’s height (54 inches) and Mark’s
height (57 inches)
다음 가격 중에 가장 작은 값과 가장 큰 값:
$34.99, $29.95, and $31.50
6
Expressions, Variables, and Assignments
>>> 2 < 3
Boolean Expressions and Operators
True
>>> 3 < 2 Boolean Expressions
False True/False를 판단하는 표현
>>> 5 - 1 > 2 + 1 Boolean types?
True #This expression is evaluated first (5-1), Only two values: True and False
and (2+1), lastly 4 > 3 Comparison operators
>>> 3 == 3 #check equality,
< (less than),
True #comparison operator “==“
> (greater than)
>>> 3 + 5 == 4 + 4
True <= (less than or equal to)
>>> 3 == 5 - 3 >= (greater than or equal to)
False != (not equal)
>>> 3 <= 4
== ( comparison)
True
>>> 3 >= 4 Boolean operators의 우선 순위는 산술 연산자보다 뒤진
False 다.
>>> 3 != 4
True x = 3에서 “=“은 할당 또는 대입 연산자!
7
Practice Problem
다음 문장을 Python expressions으로 표현하고 평가하라.
2와 2의 합이 4보다 작다.
7//3의 값은 1+1과 같다.
The sum of 3 squared and 4 squared is equal to 25.
The sum of 2, 4, and 6 is greater than 12.
1,387 is divisible by 19.
31 is even. (Hint: what does the remainder when you divide by 2 tell you?)
The lowest price among $34.99, $29.95, and $31.50 is less than $30.00.
8
Expressions, Variables, and Assignments
>>> 2 < 3 and 4 > 5
False Boolean Expressions can be
>>> 2 < 3 and True
True combined into together using
>>> 3 < 4 or 4 < 3
Boolean operators and, or, and
True
>>> 3 < 2 or 2 < 1
not
False 비교연산자의 우선 순위가 불 연산자
>>> not (3 < 4) #unary operator 보다 높다.
False
not operator :
Truth tables (반드시 숙지할 사항!) unary Boolean operator
피연산자가 하나인 연산자
9
Expressions, Variables, and Assignments
>>> x = 4 Variables and Assignments
>>> x # use the variable x
Python 에서 x = 4의 의미?
4
>>> counter = 4 * x 메모리에 변수 x 라는 이름의 공간을 만들고
# 4 * x 을 먼저 평가한 후 그 결과를 counter란 그 메모리에 4 의 값을 대입하라.
# 변수에 대입/할당/저장 또는 4의 값을 할당하라.
>>> counter #counter 에 담긴 값을 확인
할당문이라 한다. (Assignment statement)
16
변수 (variables)
>>> x 어떤 객체를 담는 그릇/바구니로 생각할 수 있다.
4 그 그릇에 담기는 객체 (또는 값)는 수시로 변경
>>> x = 7 #new assignment to variable x 될 수 있다, 그래서 변수가 된다.
>>> x
7 Python 에서는
변수의 자료형을 명시적으로 지정하지 않고 대입
하는 객체(int, float, 문자열 등등)의 형에 따라 변
수의 형이 변경된다.
10
Expressions, Variables, and Assignments
Variable Naming rules Here are some generally accepted conventions
myList and _list are OK, but 5list is not. for designing good names:
Why ? 첫번째 문자가 숫자는 안됨!!! A name should be meaningful: Name price is
list6 and l_2 are OK, but list-3 is not. better than name p.
For a multiple-word name,
Why?
use either the underscore as the delimiter
mylist and myList are different variable names.
temp_var and interest_rate
You can’t use any reserved keywords of the or use camelCase capitalization
Python language as a variable name!!! tempVar, TempVar, interestRate or
InterestRate
In this textbook,
pick one style and use it consistently
all variable names start with a lowercase throughout your program.
character.
Shorter meaningful names are better than longer
ones.
11
Strings
>>> 'Hello, World!' str (string) type
'Hello, World!'
>>> s = 'hello’ # the variable s contains a text data
#string 'hello'
>>> s
A sequence of characters,
'hello’ including blanks, punctuation
and various symbols.
'string data’ is enclosed within
quotes.
12
Strings
# comparison operators in string manipulation String Operators
>>> s == ‘hello’
True Like numbers, strings can be
>>> t = ‘world’ compared using comparison
>>> s != t
True
operators: ==, !=, < , >, and
>>> s == t so on.
False text data
>>> s < t #dictionary order
True A sequence of characters,
>>> s > t including blanks, punctuation
False
#concatenation with + operator
and various symbols.
>>> s + t 'string data’ is enclosed within
'helloworld' quotes.
>>> s + ' ' + t
'hello world'
13
Strings
>>> 3 * ‘A’ #concatenating 3 times Int * String
'AAA'
>>> 'hello ' * 2 Multiplying a string s by an
'hello hello ' integer k gives us a string
>>> 30 * '-'
'------------------------------’
obtained by concatenating k
copies of string s.
>>> s = 'hello'
>>> 'h' in s 'in’ operator
True we can check whether a
>>> 'g' in s
False
character appears in a string
>>> 'll' in s
True
>>> len(s)
5
14
Practice Problem 2.4
Start by executing the assignment statements:
>>> s1 = 'ant'
>>> s2 = 'bat'
>>> s3 = 'cod’
Write Python expressions using s1, s2, and s3 and operators +
and * that evaluate to:
'ant bat cod'
'ant ant ant ant ant ant ant ant ant ant '
'ant bat bat cod cod cod'
'ant bat ant bat ant bat ant bat ant bat ant bat ant bat '
'batbatcod batbatcod batbatcod batbatcod batbatcod '
15
Strings: indexing operator [ ]
>>> s = 'hello’ Indexing operator []
>>> s[0]
'h' The individual characters of a
>>> s[1] string can be accessed using
'e'
>>> s[4]
the indexing operator [].
'o’
>>> s[-1]
'o'
>>> s[-2]
'l'
16
Lists and Tuples
>>> pets = ['goldfish', 'cat', 'dog’] List
#The variable pets evaluates to the list: 여러 객체들의 집합
>>> pets 자료들의 집합, data collection
['goldfish', 'cat', 'dog’]
파이선에서 가장 자주 사용하는
>>>no_pets = [ ] # an empty list 자료형
a comma-separated sequence
>>> things = ['one', 2, [3, 4]]
of objects
An empty list is represented as []
Lists can contain items of
different types.
things[0] str, ‘one’
things[1] int, 2
things[2] list, [3, 4]
17
Lists and Tuples
>>> pets = ['goldfish', 'cat', 'dog’] List operators
#The variable pets evaluates to the list: Indexing operator
>>> pets
['goldfish', 'cat', 'dog’]
+, in
lst * n, n * lst
>>>no_pets = [ ] # an empty list
len(lst)
>>> things = ['one', 2, [3, 4]] max(lst), min(lst), sum(lst)
>>> pets[0]
'goldfish'
>>> pets[2]
'dog’
>>> pets[-1]
'dog’
>>> len(pets)
3
18
Lists and Tuples
>>> pets = ['goldfish', 'cat', 'dog’] List operators
>>> pets + pets # 이어 붙이기, concatenation Like strings,
['goldfish', 'cat', 'dog', 'goldfish', 'cat', 'dog'] lists can be “added,” or
>>> pets * 2 # 두 번 이어 붙이기 “concatenated.”
['goldfish', 'cat', 'dog', 'goldfish', 'cat', 'dog’] They can also be “multiplied” by
an integer k,
>>> 'rabbit' in pets
False Which means that k copies of the
>>> 'dog' in pets list are concatenated
True in operator
to check whether string 'rabbit' is
>>> lst = [23.99, 19.99, 34.50, 120.99] in the list pets
>>> min(lst)
19.99
>>> max(lst)
120.99
>>> sum(lst)
199.46999999999997 19
Lists and Tuples: Practice Problem 2.6
다음의 대입문을 수행하라.
words = ['bat', 'ball', 'barn', 'basket', 'badminton']
Now write two Python expressions that evaluate to
the first and last, respectively, word in words, in
dictionary order.
20
Lists and Tuples: Lists Are Mutable, Strings Are Not
>>> pets = ['goldfish', 'cat', 'dog’] List : mutable object !!!
# 첫번째 원소의 내용변경
>>> pets[1] = 'cymric cat’
Contents can be changed
>>> pets #변경된 내용의 확인! 원소의 내용을 변경할 수 있다.
['goldfish', 'cymric cat', 'dog’]
>>> myCat = 'cymric bat’
str : it’s immutable object.
# Following produce error Tuple: it’s immutable.
>>> myCat[7] = ‘c’ A tuple obj. can be created with
#reassign a new value
()
>>> myCat = 'cymric cat'
>>> myCat Comma-separated data
'cymric cat’ Most operations used in List
can be used in the Tuple!!
>>> days = ('Mo', 'Tu', 'We')
>>> days
Single elements tuple
('Mo', 'Tu', 'We') days = (‘Mo’,) : need comma !!!
>>> days1 = 'Mo', 'Tu', 'We', 'Th' Not days = (‘Mo’)
>>> days1
('Mo', 'Tu', 'We', 'Th') 21
Lists and Tuples: Methods
>>> numbers = [6, 9, 4, 22] Methods
>>> min(numbers) # min is called with an agr. 각 객체 (object)에 포함된 함수를
4 method 라 한다.
>>> pets = ['goldfish', 'cymric cat', 'dog’] 객체 생성시 함께 정의된 함수.
>>> pets.append('guinea pig') 정의된 객체위에서 호출될 수 있다.
>>> pets List methods are called on lists
['goldfish', 'cymric cat', 'dog', 'guinea pig’]
>>> pets.count('dog’)
2 Method calling
>>> pets.remove('dog') dot notation 을 사용한다.
>>> pets pet.append(‘dog’) list 객체 ‘pet’의
['goldfish', 'cymric cat', 'guinea pig', 'dog’] append 함수를 호출
>>> pets.reverse() Argument로 ‘dog’을 주어 함수를 호출
>>> pets 함수에 전달할 내용으로 ‘dog’이 주어짐
['dog', 'guinea pig', 'cymric cat', 'goldfish’] pet.append(‘dog’)의 의미는 list 객체
#To obtain the full listing of list methods ‘pet’에 전달인자로 전달된 str ‘dog’을 추
>>> help(list) 가하라는 의미
Help on class list in module builtins:
… 22
Lists and Tuples: Methods
To obtain the full listing of list methods, use the help()
>>> help(list)
23
Lists and Tuples: Methods
>>> pets Sort() methods
['goldfish', 'cymric cat', 'dog', 'guinea pig’]
>>> pets.sort() lst.sort()는 lst 자체를 변경하고
>>> pets 반환 값은 없다 (None!)
['cymric cat', 'dog', 'goldfish', 'guinea pig’]
>>> lst = [4, 2, 8, 5] Tuple methods
>>> lst.sort()
>>> lst count( )
[2, 4, 5, 8] index( )
List methods 가운데 원래 객체를
>>> mid_term = ( 9, 6, 8, 7, 6, 8, 7)
>>> mid_term.count(7)
변경시키지 않는 methods 만 해당!
2
>>> mid_term.index(8)
2
24
Lists and Tuples: Practice Problem 2.7
HW grade list
>>> grades = [9, 7, 7, 10, 3, 9, 6, 6, 2]
다음을 실행하는 파이선 코드를 작성하라
7 grades의 수를 찾는 표현
마지막 성적을 4로 변경하는 문장
가장 좋은 성적을 찾는 표현
A statement that sorts the list grades
An expression that evaluates to the average grade
25
Objects and Classes
To now, we show how to use several types of data that
Python supports
int
float
bool
str
list
tuple
At this point, we step back for a moment to
understand more formally
what we mean by a type, by operators and methods
supported by the type
26
Objects and Classes
객체 (Objects)
파이선에서 메모리에 저장
된 어떤 것이든 모두 객체가 type: int
된다. value: 5
객체는 메모리 공간에 존재
하는 자료형태의 한 단위이
다. type: float
자료의 단위 value: 5.0
Int, float, str 단위 etc.
메모리에 저장되는 자료을
담기 위한 상자로 생각하자. type: str
Every object has associated value: ‘Hello’
with it a type and a value.
27
Objects and Classes
>>> type(3) 객체의 타입 (Type of an object)
<class 'int’> # ask type, answered calss !!! 객체가 갖을 수 있는 자료의 형태와 그 자료형의 연
>>> type(3.0) 산을 정의한다.
<class 'float'> 객체의 type은 class 에 의하여 결정된다.
>>> type('Hello World') type () 함수
<class 'str'> 객체의 형을 알려준다.
>>> type([1, 1, 2, 3, 5, 8]) 파이선에서 변수에 type은 정의하지않고 그 변수가
현재 가리키는 객체의 형을 나타낸다.
<class 'list’>
Python is said to be object-oriented
because values are always stored in objects.
>>> a = 3
Class
>>> type(a) #show the data type of the object
클라스는 객체의 원형이다.
<class 'int'>
Class 는 객체를 정의한다.
클래스에서 객체의 자료형과 연산이 정의된다.
Type을 결정하는 곳이 class
이책에서 class와 type은 거의 같은 의미로 쓰인다.
28
Objects and Classes
>>> x = 2**1024
수 형의 타당한 값 >>> x
Valid Values for Number Types?
179769313486231590772930519078902473361
….
int 형의 타당한 값: 245938479716304835356329624224137216
형태: 3, not in a form 3.0, or three
#float type
>>> np.pi
범위도 제한 된다. 3.141592653589793
표현에 사용되는 메모리에 의하여 제한 >>> y = 2.0**30
>>> y
float 형의 값:
1073741824.0
소수점 이하를 표시하기 위하여 정수형 보다 >>> z = 2.0 ** 1024
더 많은 제약이 따른다. Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
표현 가능한 범위도 제한
z = 2.0 ** 1024
대부분 64 bit로 실수형 자료를 표현 OverflowError: (34, 'Result too large’)
아주 작은 값은 0.0으로 근사 >>> 2.0**100
1.2676506002282294e+30
>>> 2.0**-1075
29
0.0
Objects and Classes
수 형의 연산
30
Objects and Classes
비교연산
연산자 우선순위
31
Objects and Classes: Practice Problem 2.8
다음의 계산 순서를 알아보자.
(a) 2 + 3 == 4 or a >= 5
(b) lst[1] * -3 < -10 == 0
(c) (lst[1] * -3 < -10) in [0, True]
(d) 2 * 3**2
(e) 4 / 2 in [1, 2, 3]
32
Objects and Classes: Creating Objects
>>> x = 3 객체의 생성
>>> x =int(3) #명시적 생성자 호출
>>> x 변수에 지정된 형이 없으므로
3 x는 3이라는 정수형 객체를 가리
>>> x = int()
>>> x
킨다. (아래 모두 같은 의미!!!)
0 x는 3을 참조한다.
>>> y = float() 3을 지칭한다.(point to)
>>> y 3을 담고있다
0.0>>> s = str()
>>> s
명시적 생성자 호출에서 인수
'' (argument)에 의하여 그 값이 결
>>> lst = list() 정된다.
>>> lst
인수를 주지 않으면 default값을
[]
표시한다.
33
Objects and Classes: Type Conversions
>>> True + 5 암시적 형 변환
6
>>> 3 + 0.35 산술식과 논리식에서 여러
3.35 자료형의 피연산자가 사용
>>> int(3.4) 될 때 묵시적으로 모든 자료
3 형을 가장 범위가 넓은 형으
>>> int(-3.6) 로 변경한다.
-3
>>> float(3) this said to be
3.0 “broadcasting”
>>> int('3.4’) # ValueError: invalid literal for int()
with base 10: '3.4’
명시적 형 변환
>>> float('3.4') 생성자함수를 호출하여 형
3.4 변환한다.
>>> str(2.72)
'2.72'
의미가 통하지 않으면 에러
를 내준다
34
Objects and Classes: Practice Problem 2.9
다음의 연산결과가 무슨 type 인가?
(a) False + False
(b) 2 * 3**2.0
(c) 4 // 2 + 4 % 2
(d) 2 + 3 == 4 or 5 >= 5
35
Objects and Classes: Class Methods and OOP
>>> pets = ['goldfish', 'cat', 'dog'] Class (or type)
>>> pets.append('guinea pig') the set of all operators and methods that can be
>>> pets.append('dog') applied to objects of the class
methods는 class 내에서 정의된 함수이고 이 함수
>>> pets
를 호출하기위해서는 그 함수가 속해 있는 소속을
['goldfish', 'cat', 'dog', 'guinea pig', 'dog'] 명시해 줘야한다.
>>> pets.count('dog') pets.append('dog’)
2 “pets이라는 이름의 list 객체에 'dog’을 추가하는
>>> pets.remove('dog') 메소드 append를 호출하라”는 의미이고
The list method append() is called on the list
>>> pets object pets with string input ‘dog’.
['goldfish', 'cat', 'guinea pig', 'dog']
>>> pets.reverse() o.m(x,y) means
>>> pets that method m is called on object o with
['dog', 'guinea pig', 'cat', 'goldfish'] inputs x and y.
The method m should be a method of
the class object o belongs to.
O 객체가 속한 class에 정의된 m 메소드를
입력인자 x, y를 주어서 호출하라!!!
36
Objects and Classes: Class Methods and OOP
OOP : object-oriented programming
객체에 자료와 methods가 함께 정의되고 이 객체를 중심으로 프
로그래밍하는 방법을 OOP라 한다.
Imperative programming (IP)
절차적 프로그래밍
Python은 OOP, IP 모두 지원한다.
37
Python Standard Library
The core Python language is deliberately small for efficiency and ease-of-use purposes.
Python has many, many more functions and classes defined in the Python Standard Library.
The Standard Library includes modules to support, among others:
• Network programming
• Web application programming
• Graphical user interface (GUI) development
• Database programming
• Mathematical functions
• Pseudorandom number generators
38
Python Standard Library: math module
>>> import math
>>> sqrt(3) Module math
NameError: name 'sqrt' is not defined
>>> math.sqrt(3) #math module의 sqrt ( )
1.7320508075688772
>>> import fractions
>>> a = fractions.Fraction(3, 4) #3/4
>>> b = fractions.Fraction(1, 2) # 1/2
>>> a
Fraction(3, 4)
>>> c = a + b Module fractions
>>> c
Fraction(5, 4) Nice but low speed!
>>> 0.5**1075 # 0
>>> fractions.Fraction(1, 2)**1075 # Nice thing
of fractions
39
HW and Next class
HW
연습문제 2.25 ~ 2.31
Next class
Imperative Programming
40