colab link: variable
일반적으론 print() 사용하여 결과 출력
10+20
> 30
a = 10
b = 20
PI = 3.1415
print(a)
> 10
print(type(a))
print(type(PI))
> <class 'int'>
<class 'float'>
sum = a + b
print(sum)
> 30
변수 사용 시 메모리에 저장 ○
sub = a - b
print(sub)
> -10
출력만 할 경우 메모리 사용 X
print(a * b)
> 200
print(a / b)
> 0.5
print(a // b)
> 0
print(a % b)
> 10
a = [] #빈 리스트 생성
b = [1, 2, 3]
c = ["Life", "is", "too", 'short']
d = [1, 2, 'Life', 'is']
e = [1, 2, ['Life', 5]]
print(b[2])
print(d[2])
print(e[2][1])
> 3
Life
5
print(b[-1])
> 3
a = [1,2,3,4,5]
b = a[0:3] #인덱스 슬라이싱
print(b)
> [1, 2, 3]
b = a[:3] #시작 생략
print(b)
> [1, 2, 3]
b = a[2:5]
print(b)
c = a[2:] #끝 생략
print(c)
d = a[2:4]
print(d)
> [3, 4, 5]
[3, 4, 5]
[3, 4]
a = [1,2,3]
b = [4,5,6]
c = a + b
print(c)
> [1, 2, 3, 4, 5, 6]
c = []
c.append(a[0] + b[0]) #5
c.append(a[1] + b[1]) #7
c.append(a[2] + b[2]) #9
print(c)
> [5, 7, 9]
a = [1,2,3]
a.insert(0,11)
print(a)
> [11, 1, 2, 3]
d = a * 3
print(d)
> [1, 2, 3, 1, 2, 3, 1, 2, 3]
print(len(d))
> 9
a = [1,2,3,4,5]
a[2] = 10 # 값 수정
print(a)
> [1, 2, 10, 4, 5]
a = [1, 2, 10, 4, 5]
del a[2]
print(a)
> [1, 2, 4, 5]
a.remove(5) #요소 제거
print(a)
> [1, 2, 4]
b = a.pop()
print(a)
print(b)
> [1, 2]
4
a = [11, 10, 4, 2]
b = a.pop(1)
print(a)
print(b)
> [11, 4, 2]
10
a.append(3)
print(a)
a.sort()
print(a)
> [1, 2, 4, 5, 3]
[1, 2, 3, 4, 5]
a.reverse()
print(a)
> [5, 4, 3, 2, 1]
a = [10, 5, 4, 2, 1]
print(a.index(5))
> 1
a = [1,2,3,4,5,1,2,1,1]
print(a.count(1))
> 4
a = [1,2,3,4,5,1,2,1,1]
a = a + [5,4]
print(a)
> [1, 2, 3, 4, 5, 1, 2, 1, 1, 5, 4]
a += [3,2]
print(a)
> [1, 2, 3, 4, 5, 1, 2, 1, 1, 5, 4, 3, 2]
a.extend([1,0])
print(a)
> [1, 2, 3, 4, 5, 1, 2, 1, 1, 5, 4, 3, 2, 1, 0]
str_a = "hello"
print(str_a)
> hello
str_b = str_a[4]
print(str_b)
> o
str_d = '''"Python is very easy."
he sqys.'''
print(str_d)
> "Python is very easy."
he sqys.
food = 'Python\'s favorite food is perl'
print(food)
> Python's favorite food is perl
이스케이프 시퀀스(escape sequence)
\n: 줄바꿈
\': '
\t: 탭 간격
\0: NULL 문자
포맷 코드 | 설명 |
---|---|
%d | 10진수 |
%x | 16진수 |
%o | 8진수 |
%s | 문자열 |
%c | 문자 |
%f | 부동소수점 |
%% | % |
print("I eat %d apples." % 3)
> I eat 3 apples.
apple_num = 15.1
orange_num = 4.23
print("%2.2f" % apple_num)
print("%2.2f" % orange_num)
> 15.10
4.23
str_test = "I eat %d apples." % apple_num
print("Wow!!! %s" % str_test)
print("Error is %d %%." % 98)
> Wow!!! I eat 15 apples.
Error is 98 %.
b = "car,baby,code,day"
str_list = b.split(",")
print(str_list)
> ['car', 'baby', 'code', 'day']
a = "hobby"
print(a.count("b"))
> 2
a = "Python is the best choice"
print(a.find('o'))
print(a.find('z'))
> 4
-1
a = "Python is the best choice"
print(a.index('o'))
> 4
print(a.index('z'))
> ValueError: substring not found
print(",".join('abcd'))
> a,b,c,d
s = " hi "
print(s.lstrip() + "there")
print(s.rstrip())
print(s.strip() + "there")
> hi there
hi
hithere
a = "Life is too short"
b = a.replace("Life", "Your leg")
print(a)
print(b)
> Life is too short
Your leg is too short
str_list = a.split()
print(str_list)
print(type(str_list))
> ['Life', 'is', 'too', 'short']
<class 'list'>
튜플의 요소값은 한번 정하면 지우거나 변경 X.
t1 = ()
t2 = (1, )
t3 = (1, 2, 3)
print(t2 + t3)
t2 = t2 + t3 # 수정 X. 새로운 t2 생성.
print(t2)
> (1, 1, 2, 3)
(1, 1, 2, 3)
Key 값을 통해 Value 값 얻기
dic = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}
print(dic['name'])
> pey
dic[1] = 'hello' #키 추가
print(dic)
> {'name': 'pey', 'phone': '0119993323', 'birth': '1118', 1: 'hello'}
dic['name'] = 'jerry' #Value 값 변경
print(dic)
> {'name': 'jerry', 'phone': '0119993323', 'birth': '1118', 1: 'hello'}
del dic['phone']
print(dic)
> {'name': 'jerry', 'birth': '1118', 1: 'hello'}
print('류현진' in job)
print('손흥민' in job)
> True
False
job = {"김연아":"피겨스케이팅", "류현진":"야구", "박지성":"축구", "귀도":"파이썬"}
print(job.keys())
> dict_keys(['김연아', '류현진', '박지성', '귀도'])
print(job.values())
> dict_values(['피겨스케이팅', '야구', '축구', '파이썬'])
print(job.items())
> dict_items([('김연아', '피겨스케이팅'), ('류현진', '야구'), ('박지성', '축구'), ('귀도', '파이썬')])
존재 값이 없어도 오류 발생 X -> None 값 반환
print(job['손흥민'])
> KeyError: '손흥민'
print(job.get('손흥민'))
> None
순서 X. 중복 허용 X. 인덱싱 X
s = set([1,2,3])
print(s)
#print(s[2]) # error 발생
> {1, 2, 3}
intersection = s1 & s2
print(intersection)
> {8, 5, 6, 7}
intersection = s1.intersection(s2)
print(intersection)
> {8, 5, 6, 7}
union = s1 | s2
print(union)
> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
union = s1.union(s2)
print(union)
> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
difference = s1 - s2
print(difference)
difference = s2 - s1
print(difference)
> {1, 2, 3, 4}
{9, 10, 11, 12}
print(s1.difference(s2))
print(s2.difference(s1))
> {1, 2, 3, 4}
{9, 10, 11, 12}
s1 = set([1,2,3,4,5,6,7,8])
print(s1)
s1.add(9)
print(s1)
s1.update([10,11,12])
print(s1)
> {1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
s1.remove(4)
print(s1)
> {1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12}
자료형의 참과 거짓
- 문자열: True
- 빈 문자열: False
- 리스트 or 딕셔너리 값 O: True
- 리스트 or 딕셔너리 값 X: False
- 1: True
- 0: False
- None: F
a = 10
b = 10
c = 20
print(a == b)
print(a == c)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
print(a != b)
> True
False
False
False
True
True
False
print(True and False)
print(True or False)
> False
True
print(0b1101 & 0b1111) # 13 & 15
print(0b1101 | 0b1111)
> 13
15
a = [1,2,3]
print(id(a))
> 140197436357384
b = a # 참조변수
print(b)
print(id(b))
> [1, 2, 3]
140197436357384
b[1] = 4
print(a)
> [1, 4, 3]
# a와 b가 가리키는 객체는 동일한가?
print(a is b)
> True
b = a[:] # 슬라이싱 복사
print(b)
> [1, 4, 3]
print(id(a))
print(id(b)) # 주소값이 다름
print(a is b)
> 140197436357384
140197436428808
False
a = 10
b = 20
a, b = b, a
print(a)
print(b)
> 20
10
a = 10
b = 20
c = a
a = b
b = c
print(a)
print(b)
> 20
10