반응형
학습목표
- python 에서 변수 이해하기
- 기본 데이터 타입 선언하기
- int, float, str, bool
기본 데이터 타입
= 대입 연산자, == 비교 연산자
In [1]:
a = 10
print(a)
10
In [2]:
a = 'hello'
print(a)
hello
In [3]:
a == 'h'
Out[3]:
False
In [5]:
a =='hello'
Out[5]:
True
In [6]:
a == 10
Out[6]:
False
comment(주석)
In [8]:
# print(a)
print 함수
In [12]:
print(a)
a = 10
b = 20
print(a,b)
print(a,'hello',b,'hi',200)
10
10 20
10 hello 20 hi 200
- print함수 설정
- sep : 구분자, 각 출력할 변수 사이에서 구별하는 역할을 함
- end : 마지막에 출력할 문자열
In [13]:
print(a,b, sep=':')
10:20
In [14]:
print('a','b',100,200, sep = '\n',end='!!!')
a
b
100
200!!!
변수 값 확인법
- print() 함수 사용
- 변수 값을 코드의 마지막에 위치 시킨 후 실행
- 이 경우 output으로 변수의 값이 출력
In [17]:
print(a)
print(b)
10
20
variable naming (변수 이름 규칙)
- 영문 대소문자, _, 숫자 사용 가능하다.
- 대소문자 구분한다.
- 숫자로 시작 할 수 없다.
- _ 로 시작 가능하다.
- 키워드(예약어)는 사용 할 수 없다.
In [23]:
_1a = 10
oilPrice = 1850
oil_price = 2000
_import = 20
_import
Out[23]:
20
변수 여러개 한 번에 만들기
In [6]:
x, y, z = 10, 20, 30
# x, y , z = 10, 20 # 변수와 값이 짝이 맞아야 함.
x = y = z = 10
z
Out[6]:
10
reserved keywords (예약어)
- python에서 미리 선점하여 사용중인 키워드
- 변수, 함수, 클래스 등등의 사용자 정의 이름으로 사용할 수 없음
In [24]:
import keyword
print(keyword.kwlist)
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
기본 데이터 타입
- 정수 (int)
- 실수 (float)
- 문자열 (str)
- 불리언 (boolean)
type 함수
- 해당 변수, 값의 타입(type)을 알고자 할 때 사용
In [25]:
a = 10
type(a)
Out[25]:
int
In [26]:
a = 10.1
type(a)
Out[26]:
float
In [28]:
a = 'hello'
type(a)
Out[28]:
str
In [30]:
a = "hello"
type(a)
Out[30]:
str
In [31]:
a = True
type(a)
Out[31]:
bool
None
- 아무런 값을 갖지 않을 때 사용
- 일반적으로 변수가 초기값을 갖지 않게 하여 해당 변수를 생성할 때 사용
- 기타 언어의 NULL, nil등과 같은 의미로 사용
In [34]:
a = None
print(a)
del(a)
print(a)
None
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [34], in <cell line: 5>()
2 print(a)
4 del(a)
----> 5 print(a)
NameError: name 'a' is not defined
comparison operator(비교 연산자)
- 프로그래밍에서는 비교를 할 경우, = 대신 ==를 사용
- <, > (작다, 크다)
- <=, >= (작거나 같다, 크거나 같다)
- == 같다
- != 같지 않다
- 비교 연산자의 결과는 bool 타입
In [38]:
a = 4
a = 5
a > b
a == b
a != b
a <= b
Out[38]:
True
numbers (숫자형 타입)
- 정수, 실수로 구성
- 수학의 기본 연산자(가감승제) 사용 가능
In [39]:
a = 7
b = 3
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b)
print(a%b)
print(a**b)
10
4
21
2.3333333333333335
2
1
343
operator priorities (연산자 우선순위)
- 기본적인 수학의 연산자와 동일
- 강제로 연산을 선수하기 위해선, 괄호()를 사용
In [43]:
print(a + b * 4)
print((a+b) * 4)
19
40
- 연습문제 다음의 각 a값을 출력 했을 때 결과는?
In [44]:
a = 9
print(a)
print(a//3)
print(a-3)
print(a)
9
3
6
9
expression evaluation & assignment (식평가 & 대입)
- 변수의 값이 변경되기 위해서는 =를 사용하여 대입이 발생하는 경우에만 해당
In [64]:
a = 8
a - 2
print(a)
8
In [65]:
a += 2 #a = a + 2
print(a)
10
In [47]:
a -= 5 #a = a - 5
print(a)
3
In [51]:
b = 20
type(b)
Out[51]:
int
In [53]:
b = input()
20
In [50]:
print(b)
20
In [54]:
type(b)
Out[54]:
str
In [57]:
int(b) + 20
Out[57]:
40
In [60]:
b = int(input())
hello
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [60], in <cell line: 1>()
----> 1 b = int(input())
ValueError: invalid literal for int() with base 10: 'hello'
In [59]:
type(b)
Out[59]:
int
In [63]:
name = input()
False
-----------------------------------------------------------------------------------------
문자열 타입 이해
학습목표
- 문자열 이해하기
string (문자열)
- 문자 여러개가 순서대로 나열 된 것
- 문자열은 '(작은따옴표) 혹은 "(큰따옴표) 사이에 문자를 넣어서 생성
- ''' ''' 사용하여 표현 가능
- '', "" -> 한줄 문자열 표현
- ''' ''' -> 어려줄에 걸쳐 문자열 표현 가능
In [2]:
a = 'hello'
a
type(a)
Out[2]:
str
In [3]:
b = "hello"
type(b)
Out[3]:
str
In [4]:
print(a)
print(b)
hello
hello
In [7]:
c = """hello
world
!!!
"""
print(c)
hello
world
!!!
escape string
- 문자열내의 일부 문자의 의미를 달리하여 특정한 효과를 주는 것
- \n : new line \t : tab 등
In [8]:
print('nnn')
nnn
In [11]:
print('nn\nnn\tnnn')
nn
nn nnn
indexing & slicing string
- 문자열의 각 문자는 순서가 있는데, 이 순서를 인덱스 라고 한다.
- 첫번째 시작문자의 순서는 0으로 시작
In [13]:
a = 'hello world'
print(a[4])
o
In [15]:
print(a[-1])
d
In [ ]:
-1 인덱스
- python의 경우 음수 인덱스를 지원한다.
- -1이 가장 마지막 인덱스를, -2가 마지막에서 두번째 인덱스를 의미한다.
In [16]:
print(a[-3])
r
인덱스의 범위
- 인덱스는 [0, 문자열의 길이) 의 범위만 유효하다.
- 음수 인덱스를 사용할 경우, [-문자열의 길이, -1]
- 범위를 넘어갈 경우 에러 발생한다.
In [17]:
print(a[0])
h
문자열 slicing
- slicing은 부분 문자열을 추출한다.
- [시작:끝]와 같이 명시하여 (시작, 끝)에 해당하는 부분 문자열을 추출한다.
- 시작, 끝 인덱스가 생략이 되어 있다면, 0부터 혹은 끝까지로 간주한다.
In [18]:
print(a[1:3])
el
In [19]:
print(a[:4])
hell
In [20]:
print(a[3:])
lo world
In [21]:
print(a[:])
hello world
In [23]:
print(a[::3])
hlwl
문자열 함수
- 문자열은 여러가지 기능 제공을 위한 함수를 내장하고 있다.
- tab키를 이용해서 제공하는 함수들을 확인 할 수 있다.
In [24]:
type(a)
Out[24]:
str
In [29]:
aa = a.upper()
In [26]:
print(a)
hello world
In [30]:
print(aa)
HELLO WORLD
- replace
- 문자열 내의 특정 문자를 치환
In [31]:
'hello python'.upper()
Out[31]:
'HELLO PYTHON'
In [34]:
a = a.replace('l','jj')
In [35]:
a
Out[35]:
'hejjjjo worjjd'
In [40]:
#replace 문자열 바꾸기
name = 'carami hahah hoho carami'
name2 = name.replace('carami','esther')
print(name)
print(name2)
#문자 바꾸기
table = str.maketrans('aeiou','12345')
print('apple'.translate(table))
print('esther'.translate(table))
print('iulove'.translate(table))
carami hahah hoho carami
esther hahah hoho esther
1ppl2
2sth2r
35l4v2
- format
- 문자열내의 특정한 값을 변수로부터 초기화하여 동적으로 문자열을 생성
In [45]:
temp = 30
prob = 80
print(온도)
print('오늘의 기온은',temp,'도 이고, 비올 확률은',prob,'% 입니다.')
dd = '오늘의 기온은 {}도 이고, 비올 확률은 {}% 입니다. '.format(temp,prob)
print(dd)
26
오늘의 기온은 30 도 이고, 비올 확률은 80 % 입니다.
오늘의 기온은 30도 이고, 비올 확률은 80% 입니다.
In [46]:
print('hello, {}'.format('world'))
hello, world
In [47]:
print('hello, {}{}{}'.format('python','aaa',11))
hello, pythonaaa11
In [48]:
name = 'carami'
title = 'python'
number = 20
print('hello, {}{}{}'.format(name,title,number))
hello, caramipython20
In [49]:
print('hello, {2}{0}{1}'.format(name,title,number))
hello, 20caramipython
In [50]:
print('hello, {1}{2}{1}{1}{2}'.format(name,title,number))
hello, python20pythonpython20
In [52]:
print('오늘의 기온은 %d도 이고, 비올 확률은 %d 입니다. '%(temp,prob))
오늘의 기온은 30도 이고, 비올 확률은 80 입니다.
In [53]:
print(f'오늘의 기온은 {temp}도 이고, 비올 확률은 {prob} 입니다. ')
오늘의 기온은 30도 이고, 비올 확률은 80 입니다.
In [56]:
print(f'나의 이름은 {name} 입니다. 우리가 배우고 있는 것은 {title} 입니다.')
나의 이름은 carami 입니다. 우리가 배우고 있는 것은 python 입니다.
- split
- 문자열을 특정한 문자 구분하여(delimiter) 문자열의 리스트로 치환
In [57]:
a = 'hello world what a nice weather'
a.split()
Out[57]:
['hello', 'world', 'what', 'a', 'nice', 'weather']
In [58]:
a.split('w')
Out[58]:
['hello ', 'orld ', 'hat a nice ', 'eather']
In [59]:
#문자열 분리하기 split()
result = 'apple pear grape pineapple orange'.split()
print(result)
result = 'apple, pear, grape, pineapple, orange'.split(',')
print(result)
['apple', 'pear', 'grape', 'pineapple', 'orange']
['apple', ' pear', ' grape', ' pineapple', ' orange']
In [60]:
a = input()
10 20
In [61]:
print(a)
10 20
In [64]:
a, b = input().split(',')
print(a)
print(b)
10,20
10
20
- join
- 구분자 문자열과 문자열 리스트 연결하기
In [65]:
print(result)
['apple', ' pear', ' grape', ' pineapple', ' orange']
In [66]:
#구분자 문자열과 문자열 리스트 연결하기 join
joinStr = ' '.join(result)
print(joinStr)
apple pear grape pineapple orange
In [67]:
type(result)
Out[67]:
list
In [68]:
type(joinStr)
Out[68]:
str
In [70]:
joinStr = ','.join(result)
print(joinStr)
apple, pear, grape, pineapple, orange
In [71]:
print(',,'.join(['aa','bb','cc']))
aa,,bb,,cc
* **공백삭제**
In [84]:
t = ' python'
t2 = ' python '
t3 = 'python '
print(t2 == t3)
print(t == t2)
print(t.strip())
print(t.strip() == t2.strip())
print(t2.strip())
print(t3.strip() == 'python')
print(t.lstrip())
print(' hello '.strip())
print(' hello '.lstrip())
print(' hello '.rstrip())
False
False
python
True
python
True
python
hello
hello
hello
- 특정문자삭제
In [86]:
print(',. he,.llo ,.'.strip(',.'))
he,.llo
In [109]:
#구두점을 간단하게 삭제하기
import string
print(string.punctuation)
print(' #$!@%$#%#python#@^$@'.strip(string.punctuation+' '))
#문자열 왼쪽 정렬하기
print('hello'.ljust(10))
print('hello'.rjust(10))
print('hello'.center(10))
#메서드체이닝
str1 = 'hello'.upper().rjust(15).split('L')
print(str1)
#문자열 위치찾기 find, rfind, index, rindex
'python hello carami haha'.find('h')
'python hello carami haha'.find('xi')
'python hello carami haha'.rfind('h')
'python hello carami haha'.index('h')
'python hello carami haha'.rindex('h')
#문자열개수세기
'python hello carami haha'.count('python')
#'python hello carami haha'.index('xi')
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
python
hello
hello
hello
[' HE', '', 'O']
Out[109]:
1
In [125]:
#비교연산 is 같은 객체인 is not 같은 객체가 아닌.. x or y , x and y , not x
name = 'kang'
name2 = 'kang'
print(name == name2)
print(name is name2)
print(name is not name2)
print(name, id(name))
print(name2, id(name2))
#문자열 타입
#데이터가 여러 문자로 구성되어 있고 다른 문자와 연결될 수 있으며 데이터에 포함된 문자열의 길이를 확인 할 수 있는 데이터 타입
#파이썬에서 문자열 데이터 타입은 str 여러줄로 표현할때는 ''' ''' 또는 """ """
print('hi'*10)
'test hello carami'.startswith('t')
'test hello carami'.endswith('mi')
True
True
False
kang 2598400313648
kang 2598400313648
hihihihihihihihihihi
Out[125]:
True
In [119]:
#변할 수 없는 (immutable) vs 변할 수 있는 (mutabel)
test = [1,2]
test2 = [1,2]
print(test == test2)
print(test is test2)
print(test, id(test))
print(test2, id(test2))
True
False
[1, 2] 2598400752640
[1, 2] 2598400775808
'경기도 인공지능 개발 과정 > Python' 카테고리의 다른 글
Python 파일 입출력 (0) | 2022.05.28 |
---|---|
Python 함수, lambda 함수 (0) | 2022.05.28 |
Python 조건문과 반복문(While, For) (0) | 2022.05.28 |
Python 컬렉션 타입 (0) | 2022.05.28 |
Python 주피터 노트북 사용법 (0) | 2022.05.28 |