Python - 자료형, 반복문, 함수, class

양희연·2020년 5월 1일
0

Python

목록 보기
1/10
post-thumbnail

💻 입력

input()
문자열로 반환

#결과값 정수로 변환
a = int(input())

#함수 split() 이용
a, b = input().split()

#파이썬 내장함수 map() 이용
a, b = map(int, input().split())

🖨 출력

print()

print(1, 2, 3)
#출력결과
#1 2 3

print(1, 2, 3, sep='/')
#출력결과
#1/2/3

#end: 출력 끝의 값을 지정한다. default 값 \n
print('', end = '')



💾 자료형

  • number int float complex
  • string str
  • boolean - True(1) False(0)
  • list
  • tuple
  • dictionary
  • set

💡 자료형 확인하는 함수 type()

💡 자료형 변환 가능.
int(), float(), complex(), str(), list(), tuple() ...




𝓧 변수

규 칙
영어 알파벳, 숫자 그리고 _ 로만 구성될 수 있다.
첫 글자로 숫자를 쓰면 안된다.
영어 알파벳의 대소문자 구분이 된다.
키워드를 사용하지 못한다.

a, b, c = 1, 2, 3
print(a, b, c)
#출력결과
#1 2 3



📝 문자열

값을 변경할 수 없으며, 순서가 있다.

> f-strings

name = input()
print(f'hello, {name}!')

> indexing

0부터 시작한다.
공백도 포함한다.
음수도 가능하며, 마지막 값을 -1부터 해서 거꾸로 센다.

> method

💡 method: 해당 자료형에서 쓸 수 있는 함수

split()
parameter 기준으로 문자열을 분리하여 리스트 형태로 반환한다. default 값은 공백이다.

color = 'red/green/blue'
colors = color.split('/')
print(colors)
#출력결과
#['red', 'green', 'blue']



[List]

값들은 변경할 수 있고 순서가 있다.
서로 다른 data type의 값을 저장할 수 있다.

my_string = 'smart'

print(list(my_string))
#출력결과
#['s', 'm', 'a', 'r', 't']

print([my_string])
#출력결과
#['smart']

> indexing, slicing

colors = ['red', 'green', 'blue']

#정해진 리스트 길이안에서 수정만 가능. 추가는 안됨
colors[2] = 10
print(colors)                       #['red', 'green', 10] 

print(colors[0])                    #red
print(colors[1:])                   #['green', 10]
print(colors[::2])                  #['red', 10]
print(colors[-2:-1])                #['green']
print(colors[1:-1])                 #['green']
print(colors[:-1])                  #['red', 'green']
print(colors[2:0:-1])               #[10, 'green']

#삭제
del colors[0]
print(colors)                       #['green', 10]

💡 slicing은 original list를 수정하는 게 아니라, 새로운 list를 만들어낸다.

💡 [start_index : stop : step]
      stop에 -1 한 index 까지
      역순(🔙)일 때는 +1 한 index 까지

> method

append()
요소 하나를 리스트 끝에 추가한다.

numbers = [1, 2, 3]
print(numbers.append(10))
#출력결과
#[1, 2, 3, 10]

+
추가할 요소가 여러 개인 경우 사용

numbers = [1, 2, 3]
numbers = numbers + [10, 20, 30]
print(numbers)
#출력결과
#[1, 2, 3, 10, 20, 30]

pop()
해당 인덱스의 값이 반환되면서 삭제된다. 기본값은 마지막 인덱스이다.

numbers = [1, 2, 3, 4, 5]
numbers.pop()
print(numbers)
#출력결과
#[1, 2, 3, 4]

numbers.pop(2)
print(numbers)
#출력결과
#[1, 2, 4]

remove()
특정 값을 삭제한다. 중복될 경우 처음 찾은 값을 삭제한다.

numbers = [1, 2, 1]
numbers.remove(1)
print(numbers)
#출력결과
#[2, 1]

💡 요소가 리스트에서 삭제되면 자동으로 리스트의 인덱스들을 다시 정렬한다.

reverse() & reversed()
reverse()는 값의 순서를 뒤집는다. 기존 list의 값이 바뀐다
reversed() 원본은 그대로이며, 바뀐 값으로 리스트를 생성한다.

numbers = [1, 3, 2]
numbers.reverse()
print(numbers)
#출력결과
#[2, 3, 1]

join()
리스트에 특정 구분자를 추가하여 문자열로 변환한다. 단, 리스트의 요소가 문자열 이어야 한다.

my_list = ['a', 'b', 'c']

print('/'.join(my_list))
#출력결과
#a/b/c

numbers = [1, 2, 3]
print('/'.join(map(str, numbers)))
#출력결과
#1/2/3

sort() & sorted()
sort()는 기존 리스트를 정렬하고, sorted()는 정렬한 리스트를 생성해준다.

> list comprehension

간결하고 데이터베이스를 조회하여 리스트로 만들때 많이 사용된다.
list comprehension 이 for loop 문보다 약 2배 정도 빠르긴 하지만, 가독성이 좋지 않거나 복잡한 for문 경우에는 권장하지 않는다.

new_list = [2**i for i in range(5) if i % 2 == 0]
print(new_list)
#출력결과
#[1, 4, 16]

💡 range(시작숫자, 종료숫자, step)
    시작숫자부터 종료숫자 바로 전 숫자까지 연속된 숫자(정수)를 만들어낸다.
    시작숫자와 step은 생략가능하다. 시작숫자 생략 시 값은 0이다.




(Tuple)

값을 변경할 수 없고, 추가할 수 없다. 삭제 또한 할 수 없다.
서로 다른 data type 값을 저장할 수 있다.
괄호를 쓰지 않아도 된다.

my_tuple = (1, 2)

#출력될 튜플이 요소 하나면 ,가 붙는다.
print(my_tuple[:1])
#출력결과
#(1, )

list와 tuple

tuple은 일반적으로 2개에서 5개 사이의 요소들을 저장할 때 사용한다.
수정이 필요없고 간단한 형태의 데이터를 표현할 때 tuple을 사용하는 게 더 효율적이다.



{dictionary}

key는 중복될 수 없으며, 변하지 않는 값만이 key가 될 수 있다.

my_dict = {}
my_dict[1] = 'one'
my_dict['two'] = 2
print(my_dict)
#출력결과
#{1: 'one', 'two': 2}

#수정
my_dict[1] = 100
print(my_dict)
#출력결과
#{1: 100, 'two': 2}

#삭제
del my_dict[1]
print(my_dict)
#출력결과
#{'two': 2}

> method

get(키, 해당 키가 없을 경우 반환할 값)
키에 해당하는 값을 반환한다.

my_dict = {1: 'one', 'two': 2}
print(my_dict.get(3, 'three'))
#출력결과
#three

> 딕셔너리와 반복문

#keys
my_dict = {1: 'one', 'two': 2}

for key in my_dict:
    print(key)

#values
my_dict = {1: 'one', 'two': 2}

for value in my_dict.values():
    print(value)

#items
my_dict = {1: 'one', 'two': 2}
print(my_dict.items())
#출력결과
#dict_items([(1, 'one'), ('two', 2)])

for key, value in my_dict.items():
    print(key, value)

> 내장함수 zip()

동일한 개수로 이루어진 자료형을 튜플로 묶어준다.
여러 개의 iterable을 사용 가능

my_num = [1, 2, 3]
my_str = ['a', 'b', 'c']
for i, j in zip(my_num, my_str):
    print(i, j)          
#출력결과
#(1, 'a')
#(2, 'b')
#(3, 'c')

#zip을 이용한 리스트 만들기
my_num = [1, 2, 3]
my_str = ['a', 'b', 'c']
num_str = list(zip(my_num, my_str))
print(num_str)
#출력결과
#[(1, 'a'), (2, 'b'), (3, 'c')]

#zip을 이용한 딕셔너리 만들기
my_num = [1, 2, 3]
my_str = ['a', 'b', 'c']
my_dict = dict(zip(my_num, my_str))
print(my_dict)
#출력결과
#{1: 'a', 2: 'b', 3: ‘c'}



📐 연산자

> 산술연산자

+
-
*
/     나누기의 몫이 실수로 반환
//   나누기의 몫이 정수로 반환
%     나누기의 나머지
**

🚗 연산 순서 ()***, /, %+. -

> 단락평가

print(True and 'Python')             #Python
print(0 and 'Python')                #0

print(True or 'Python')              #True
print('Python' or True)              #Python
print(False or 'Python')             #Python
print(0 or False)                    #False



🎡 반복문

파이썬에는 for, while 반복문이 있다.
for는 list, set, dictionary 등 자료구조를 기반으로 코드블럭을 반복 실행한다.
while는 특정 조건문이 True일동안 코드블록을 반복 실행한다.

💡 enumerate()
    순서가 있는 자료형을 입력으로 받아 인덱스 값을 포함하는 객체를 반환하다.

alphabet = ['a', 'b', 'c', 'd']
for i in enumerate(alphabet):
    print(i)
#실행결과
#(0, 'a')
#(1, 'b')
#(2, 'c')
#(3, 'd')

> break, continue

#break: 반복문을 끝낸다
for i in range(5):
    if i == 3:
        print('3을 찾았습니다. 반복문을 종료하겠습니다.')
        break
    else:
        print('3을 찾지 못했습니다.')

#continue: 다음 interation으로 돌아간다.
for i in range(5):
    if i < 3:
        continue
    else:
        print('3 이상입니다.', i)

> 중첩 for

for i in range(2, 10):
    for j in range(1, 10):
        print(f'{i} * {j} = {i*j}')

#list complihension 사용
#[i * j for i in range(2, 10) for j in range(1, 10)]



🔩 Function

#return 값을 여러개 받을 때는 하나의 튜플로 묶어서 반환한다.
def 함수이름(parameter):          
    return 반환값
def test():
    return 1, 2
#실행결과
#(1, 2)

#return이 실행되는 즉시 그 함수는 실행 종료된다.
def end():
    return 'hello'
    print('world')

print(end())
#출력결과
#hello

#return 값이 없으면 함수 결과값은 None을 반환한다.
def no_return(x, y):
    z = x + y

result = no_return(1, 2)
print(result)
#출력결과
#None

> first class function

함수를 값으로 다룰 수 있는 것 (함수 스스로 객체 취급)
👉 즉, 함수를 변수나 데이터 구조 안에 담을 수 있으며, 함수에 인수로 전달이 가능하고, 리턴값으로 사용될 수 있다.

def hello():
    print('hello')

#함수를 greeting 변수에 할당
greeting = hello

#greeting 변수 끝에 괄호를 추가하여 함수 호출
print(greeting())
#출력결과
#hello



🏫 class

car 👉 class
bmw, benz, hyundai 👉 object

💡 객체
property와 method를 모아 놓은 것

#클래스명 첫 문자는 대문자
class Database:
    #대표적 매직 메소드 __init__, __str__
    def __init__(self, name):
        self.name = name
        self.db   = {}
    
    #method
    def insert(self, field, value):
        self.db[field] = value

    def select(self, field):
        if field in self.db:
            return self.db[field]
        else:
            return None
      
    def update(self, field, value):
        if field in self.db:
            self.db[field] = value
  
    def delete(self, field):
        if field in self.db:
            del self.db[field]

#객체 생성
data1 = Database('bmo')
data1.insert(age, 20)
  • __init__
    객체를 생성할 때 자동으로 호출된다.
  • self
    class의 instance를 가리킨다.

> 상속

#MoreDatabase는 Database의 모든 기능을 사용할 수 있다.
class MoreDatabase(Database):
    #method overwriting: 부모클래스와 동일한 명의 method를 작성하는 것
    #select method 호출 시 부모에 있는 함수가 아니라 오버라이딩된 함수가 호출된다.
    def select(self):
        return self.db


참고자료 : 김왼손의 미운코딩새끼, 코딩도장

profile
꾸준히 나아가자!

0개의 댓글