본문 바로가기
프로그래밍/back end 백 엔드

python 기초

by 어느덧중반 2021. 7. 7.
반응형

- variable

- List : [1, 2, 3], Tuple : (1, 2, 3), Dictionary : {'a': 1, 'b': 2, 'c': 3}

- json하고 형식이 같다. 기존 선언해둔 kyungsnim에 속성 추가도 바로 가능하군

 

- 문자열 포맷팅

  * % 연산자를 이용해 문자열에 숫자, 문자열 대입이 가능

>>> print('My name is %s' % 'Tom')
My name is Tom
>>> print('x = %d, y = %d' % (1, 2))
x = 1, y = 2
>>> print('%f' % 3.14)
3.14

 

- format()

  * % 연산자보다 더 파이썬같은 대입법

>>> print('My name is %s' % 'Bob')
My name is Bob
>>> print('My name is {}'.format('Bob'))
My name is Bob
>>> print('{} x {} ={}'.format(3, 4, 3 * 4))
3 x 4 = 12
>>> print('{1} x {0} ={2}'.format(3, 4, 3 * 4))  # 차례대로 넣을 순서 지정 가능
4 x 3 = 12


- 인덱싱

  * index를 이용해 문자에 접근하는 방식 (0부터 시작)

>>> tmp = 'abcdefghi'
>>> print(tmp[0])
a
>>> print(tmp[4])
e
>>> print(tmp[10])
IndexError: string index out of range
>>> imsi = '공백 넣어보기'
>>> imsi[1]
백
>>> my_name[6]
기

  * 음수를 이용하면 뒤에서부터 거꾸로 세어간다.

>>> name = '황경스님'
>>> name[-1]
님

 

- 문자열 슬라이싱

  * 문자열의 여러 값 잘라서 가져오기 (콜론(:)을 이용해 가져온다.)

>>> tmp_str = 'Jamsil Station'
>>> print(tmp_str[0:3])
Jam
>>> print(tmp_str[3:8])
sil S

  * 앞, 뒤 생략 가능

>>> print(tmp_str[:4])
Jams
>>> print(tmp_str[5:])
l Station


- split() 메소드

  * 문자열을 공백 기준으로 분리해주는 메소드

>>> color_str = 'red orange yellow green blue'
>>> split_str = color_str.split()
>>> print(split_str[0])
red
>>> print(split_str[1])
orange
>>> print(split_str[4])
blue
>>> print(color_str.split())
['red', 'orange', 'yellow', 'green', 'blue']

 

- 리스트

  * 값 추가하기

>>> number = [1, 2, 3]
>>> number.append(5)
>>> number.append(4)
>>> print(number)
[1, 2, 3, 5, 4]

  * 인덱싱, 슬라이싱 (문자열과 비슷하게 쓰면 된다)

>>> number = [1, 2, 3]
>>> print(number[2])
3

  * 정렬하기 : sort(), 카운트 : count()

>>> number = [1, 2, 3]
>>> number.append(5)
>>> number.append(4)
>>> print(number)
[1, 2, 3, 5, 4]
>>> number.sort()
>>> print(number)
[1, 2, 3, 4, 5]
>>> number.append(5)
>>> number.append(5)
>>> print(number)
[1, 2, 3, 4, 5, 5, 5]
>>> number.count(5)
3

 

- 튜플

  * 기본 구조 : 괄호안에 넣어서 만들거나 콤마구분으로 바로 만들 수 있다.

>>> tuple_array = 1, 2, 3, 4, 5, 6
>>> tuple_array2 = (1, 2, 3, 4, 5, 6)
>>> list_array = [1, 2, 3, 4, 5, 6]
>>> print(type(tuple_array))
<type 'tuple'>
>>> print(type(tuple_array2))
<type 'tuple'>
>>> print(type(list_array))
<type 'list'>

  * 패킹 (여러개 값 한꺼번에 묶기 -> 흔히 쓰는 튜플), 언패킹 (묶여있는 튜플을 풀어 저장하기)

>>> tuple_array = 1, 2, 3, 4, 5, 6
>>> num1, num2, num3, num4, num5, num6 = tuple_array
>>> print(num2)
2
>>> print(num4)
4

  * 로테이션 (바꾸기)

>>> num1 = 1
>>> num2 = 2
>>> num1, num2 = num2, num1
>>> print(num1)
2
>>> print(num2)
1

 

- for

>>> x = [1, 2, 3, 4, 5]
>>> for a in x:
	print(a)

1
2
3
4
5

# 구구단 출력하기
>>> for j in range(2, 10):
    	for i in range(1, 10):
        	print('{} x {} = {}'.format(j, i, j * i))

 

- range() : for와 함께 쓰이는 내장함수

  * 사용법

   1) range(number) : 0부터 number 전까지 숫자 나열

   2) range(start, stop) : start부터 stop 전까지 숫자 나열

>>> for n in range(5):
	print(n)
0
1
2
3
4
>>> for n in range(5, 7):
	print(n)	
5
6

 

- comprehension (컴프리헨션) : 리스트를 만드는 간결한 표현

>>> # 리스트에서 홀수만 뽑기
>>> arrays = [1, 2, 3, 4, 5, 6, 7]
>>> odd = []
>>> odd = [num for num in arrays if num % 2 == 1]
>>> print(odd)
[1, 3, 5, 7]

 

- membership (멤버십) : 리스트, 튜플 안에 해당 값의 유무 확인

  * in, not in 등의 키워드 사용

>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']
>>> print('red' in colors)
True
>>> print('red' not in colors)
False
>>> print('black' in colors)
False
>>> print('black' not in colors)
True

 

- dictionary (딕셔너리) : key와 value로 이루어진 구조

  * 내장함수 : .value() / .keys() / .items()

>>> apart = {'이매동': '삼환아파트', '여수동': '산들마을', '서현동': '한양아파트'}
>>> for x in apart.values():
	print(x)
한양아파트
삼환아파트
산들마을

>>> for x in apart.keys():
	print(x)
서현동
이매동
여수동

>>> for x in apart.items():
	print(x)
('\xbc\xad\xc7\xf6\xb5\xbf', '\xc7\xd1\xbe\xe7\xbe\xc6\xc6\xc4\xc6\xae')
('\xc0\xcc\xb8\xc5\xb5\xbf', '\xbb\xef\xc8\xaf\xbe\xc6\xc6\xc4\xc6\xae')
('\xbf\xa9\xbc\xf6\xb5\xbf', '\xbb\xea\xb5\xe9\xb8\xb6\xc0\xbb')

 

- 함수

# 인자 넘겨받아 리턴시켜주기
>>> def add_func(num1, num2):
	return num1+num2

>>> add_num = add_func(100, 200)
>>> print(add_num)
300

# 멀티 리턴 가능
>>> def add_minus(num1, num2):
	return num1+num2, num1-num2

>>> add_num, minus_num = add_minus(100, 60)
>>> print(add_num, minus_num)
(160, 40)

 

- random : import를 이용해 라이브러리를 가져다 쓸 수 있다.

# random 모듈 가지고 오기
>>> import random

>>> colors = ['red', 'orange', 'yellow', 'green', 'blue']

# colors 중 랜덤으로 선택하기
>>> print(random.choice(colors))
green
>>> print(random.choice(colors))
yellow
>>> print(random.choice(colors))
orange
>>> print(random.choice(colors))
yellow
>>> print(random.choice(colors))
yellow
>>> print(random.choice(colors))
green

# colors 중 2개 랜덤으로 뽑기
>>> print(random.sample(colors, 2))
['orange', 'blue']
>>> print(random.sample(colors, 2))
['red', 'green']
>>> print(random.sample(colors, 2))
['yellow', 'blue']
>>> print(random.sample(colors, 2))
['yellow', 'orange']

# 0부터 100까지 숫자 중 랜덤으로 뽑기
>>> print(random.randint(0, 100))
71
>>> print(random.randint(0, 100))
85
>>> print(random.randint(0, 100))
6
>>> print(random.randint(0, 100))
28

 

반응형

댓글