Lesson 01: 파이썬의 자료형 I (int, float, bool, str)

Author

최규빈

Published

January 30, 2023

ref

https://guebin.github.io/IP2022/2022/03/07/(1주차)-3월7일.html#자료형

Intro

- 파이썬의 기본자료형은 int, float, bool, str, list, tuple, dict, set 등이 있다.

  • 0차원 자료형: int, float, bool
  • 1차원 자료형: str, list, tuple, dict, set

int, float, bool

- int형

a=100
type(a)
int

- float형

a=1.2*3
a
3.5999999999999996
type(a)
float
a?
Type:        float
String form: 3.5999999999999996
Docstring:   Convert a string or number to a floating point number, if possible.

- bool형

a=True ## 숫자1으로 생각할 수 있음 
b=False ## 숫자0으로 생각할 수 있음
type(a)
bool
type(b)
bool
a?
Type:        bool
String form: True
Docstring:  
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
b?
Type:        bool
String form: False
Docstring:  
bool(x) -> bool
Returns True when the argument x is true, False otherwise.
The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.

- bool형의 연산

a=True ## 1
b=False ## 0 
a+b
1
a*b 
0

- complex형

a=1+2j
b=2-2j
type(a)
complex
type(b)
complex
a?
Type:        complex
String form: (1+2j)
Docstring:  
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.
b?
Type:        complex
String form: (2-2j)
Docstring:  
Create a complex number from a real part and an optional imaginary part.
This is equivalent to (real + imag*1j) where imag defaults to 0.
c=a+b
c
(3+0j)

- 형태변환: float \(\to\) int

(예시1)

a=3.0
type(a)
float
a=int(a)
type(a)
int

(예시2) 이경우는 정보의 손실이 발생

a=3.14 
int(a)
3

- 형태변환: int \(\to\) float

a=3
type(a)
int
a=float(a)
type(a)
float

- 형태변환: bool \(\to\) int/float, int/float \(\to\) bool

(예시1)

a=True
type(a)
bool
int(a)
1
float(a)
1.0

(예시2)

a=1 
bool(a)
True
a=0
bool(a)
False

(예시3)

a=1.0
bool(a)
True
a=0.0
bool(a)
False

- 이상한 형태변환도 가능하다. (이런것도 바꿔주나 싶은것도 바꿔줌)

bool(-3.14)
True
  • 저는 이런 코드를 의도적으로 사용하지 않아요..
int(3.14)
3

- 형태변환이 항상가능한것도 아님

float(3+0j) # 사실상 3+0j=3 이므로 float으로 형변환하면 3.0이 되어야 할 것 같은데 변환불가능하다. 
TypeError: can't convert complex to float

- 암묵적형변환 (implicit)

(예비학습) implicit의 의미 - 추운날씨 -> 보일러좀 틀자! (explicit) / 오늘 날씨 좀 추운 것 같지 않아? (implicit) - 짜장면 먹을래? -> 싫어! (explicit) / 난 어제 짜장면 먹었는데.. (implicit)

(예제)

True * 1 # 1을 곱할건데 너 계속 True로 있을꺼야? 
1
1 * 1.0 # 1.0을 곱할건데 너 계속 int로 있을꺼야? 
1.0
True+True # +연산을 할건데 계속 True로 있을꺼야? 
2

str

선언

a='guebin'
a
'guebin'

연산

- 더하기(+)연산

a='X'
b='2'
c=a+b
c
'X2'

- 빼기(-)연산

a='X2'
b='2'
a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
  • 이런건 없다.

- 곱하기(*)연산

a='X'
a+a+a
'XXX'
a*3 # a*3 = a+a+a = 'X'+'X+'X'
'XXX'

아래도 가능하다.

3*a
'XXX'

그리고 아래도 가능하다.

a='X'
b=3 
a*b
'XXX'

대신에 의미상 맞지 않는 것은 수행되지 않고 에러가 난다.

a='X'
b='Y'
a+b
'XY'
a*b
TypeError: can't multiply sequence by non-int of type 'str'

- 나눗셈(/)연산

a='XX'
a/2
TypeError: unsupported operand type(s) for /: 'str' and 'int'
  • 이런건 없다..

인덱싱

- str은 하나의 벡터 문자가 여러개 있는 형태라고 생각하면 된다.

a='guebin'
a
'guebin'
  • 6개의 칸에 글씨가 하나씩 들어가 있음.

- 대괄호 []안에 숫자를 넣는 방식으로 벡터의 원소를 호출할 수 있다. (주의: 인덱스가 0부터 시작함)

a[0] #첫번째원소
'g'
a[1] #두번째원소 
'u'

마지막원소는 -1로 호출할 수도 있다.

a[-1]
'n'

마지막에서 2번째 원소는 -2로 호출가능하다.

a[-2]
'i'

- 요약하면 아래와 같은 방식으로 호출가능함.

g u e b i n
0 1 2 3 4 5
0 -5 -4 -3 -2 -1
a[4]
'i'
a[-2]
'i'
a[-4]
'e'

- :을 이용하여 여러개의 원소를 호출할 수 있음.

a='guebin'
a[0:3] # a[0],a[1],a[2],a[3]이 아니라 a[0],a[1],a[2]까지만 뽑힌다. 즉 마지막의 3은 호출되지 않는다. 
'gue'
a[1:3] # a[1], a[2] 만 호출 // start=1,  stop=3 
'ue'

index=1부터 시작해서 마지막원소까지 호출하려면?

a[5] # guebin의 마지막원소 'n'이 출려 
'n'
a[1:5] # 5는 포함되지 않으므로 틀림
'uebi'
a[1:6] # 정답
'uebin'

안 헷갈리는 방법은 없을까?

a[-1]
'n'
a[1:-1] # 이것은 결국 (a[1:5]와 같은 것임) 
'uebi'

해결책? 생략한다!!

a[1:]
'uebin'

- 생략의 응용1

a='k-pop' 
a
'k-pop'
a[2:5]
'pop'
a[2:]
'pop'

- 생략의 응용2

a='k-pop'
a
'k-pop'
a[0:2] # a[0],a[1]
'k-'
a[:2] # a[0],a[1] 
'k-'

- 생략의 응용3

a='k-pop'
a
'k-pop'
a[0:5] # a[0],...,a[4]
'k-pop'
a[:]
'k-pop'

str 특수기능

- 파이썬의 변수는 단순히 정보를 담는 그릇이 아니다. 유용한 기능을 제공하는 경우가 있다.

a='ABCD' # a라는 변수는 'ABCD'라는 정보를 담는 그릇의 역할만 하지 않고, 특화된 어떠한 기능도 제공한다. 
a
'ABCD'
a.lower() # a.lower()를 쓰면 a의 모든 문자를 소문자로 바꾸는 기능을 제공, lower(a)라고 읽자!
'abcd'

여기에서 lower()는 문자열에 특화된 기능임. 따라서 당연히 아래는 불가능

a=3.14
a.lower() # lower(a)
AttributeError: 'float' object has no attribute 'lower'

- 자료형에 특화된 기능(=함수)을 확인하는 방법? a.+ tab 으로 목록 확인 가능

a='guebin'
a.upper?
Signature: a.upper()
Docstring: Return a copy of the string converted to uppercase.
Type:      builtin_function_or_method
a.upper() # upper(a) 
'GUEBIN'
a.capitalize() # capitalize(a) 
'Guebin'

- 문자열에 대한 다른 내용들은 추후에 다루겠음.

- 마음의눈: a.f() 형태를 읽는 팁 - a.f()f(a)로 생각하면 편리함. - a.f(2)f(a,2)로 생각하면 편리함. - 이런점에서 R %>% 연산자와 비슷하다고 생각할 수 있다. (약간 다르긴함)

- 사실 .은 좀 더 다양한 상황에서 쓰일 수 있다. 변수이름.함수이름() 의 형태가 아니라 - 패지키이름.함수이름() - 패키지이름.변수이름 - 패키지이름.패키지이름.함수이름() - …

와 같이 다양한 형태가 가능하다. 근본적인 공통점은 .을 기준으로 상위개념.하위개념 으로 이해하는 것이 좋다.

0차원 vs 1차원

- len함수 소개: 원소의 갯수를 알려주는 함수.

(0차원) len 함수가 동작하지 않음.

a=3.14
len(a)
TypeError: object of type 'float' has no len()
b=True
len(b)
TypeError: object of type 'bool' has no len()

(1차원) len 함수가 잘 동작함.

a='3.14'
len(a)
4
b=[1,2,3]
len(b)
3

Quiz

본인이름으로 str을 생성

  • 성만 출력
  • 이름만 출력

(예시)

a='GuebinChoi'
a[:6]
'Guebin'
a[6:]
'Choi'