[Python]_문법 중에 헷갈리는 것 모음집!

hanseungjune·2023년 2월 5일
0

비전공자의 IT준비

목록 보기
42/68
post-thumbnail

일단 Python은 사실 이미 싸피 1학기때 했기 때문에 문법 중에서 헷갈리는 것만 여기다가 올려 놓을 계획이다. 실력이 점차 감소하고 있어서... 글이 길어질수도 있음 ㅎ

📌 Array

# 선언
a = []
b = list()
c = [70, 75, 80, 85]
d = [1000, 10000, 'Ace', 'Base', 'Captine']
e = [1000, 10000, ['Ace', 'Base', 'Captine']]
f  = [21.42, 'foobar', 3, 4, 'bark', False, 3.14159]

💫 리스트 수정, 삭제

c[0] = 4
print('c - ', c)
c[1:2] = ['a', 'b', 'c'] # [['a', 'b', 'c']]
print('c - ', c)
c[1] = ['a', 'b', 'c']
print('c - ', c)
c[1:3] = []
print('c - ', c)
del c[3]
print('c - ', c)
c -  [4, 75, 80, 85]
c -  [4, 'a', 'b', 'c', 80, 85]
c -  [4, ['a', 'b', 'c'], 'b', 'c', 80, 85]
c -  [4, 'c', 80, 85]
c -  [4, 'c', 80]

💫 리스트 정렬, 추가, 카운팅, 인덱스 등등

print('a - ', a)
print('a - ', a.index(5))
a.insert(2, 7)
print('a - ', a)
a.reverse()
a.remove(1)
print('a - ', a)
print('a - ', a.pop())
print('a - ', a.pop())
print('a - ', a)
print('a - ', a.count(4))
ex = [8, 9]
a.extend(ex)
print('a - ', a)
a -  [6, 5, 4, 3, 2, 1]
a -  1
a -  [6, 5, 7, 4, 3, 2, 1]
a -  [2, 3, 4, 7, 5, 6]
a -  6
a -  5
a -  [2, 3, 4, 7]
a -  1
a -  [2, 3, 4, 7, 8, 9]

📌 Dict

# 선언
a = {'name': 'Kim', 'phone': '01012345678', 'birth': '870124'}
b = {0: 'Hello python!'}
c = {'arr': [1, 2, 3, 4]}
d = {
	 'Name' : 'Niceman',
	 'City'   : 'Seoul',
	 'Age': '33',
	 'Grade': 'A',
	 'Status'  : True
}
e =  dict([
	 ( 'Name', 'Niceman'),
	 ('City', 'Seoul'),
	 ('Age', '33'),
	 ('Grade', 'A'),
	 ('Status', True)
])

f =  dict(
	 Name='Niceman',
	 City='Seoul',
	 Age='33',
	 Grade='A',
	 Status=True
)

👌 출력형식

print('a - ', a['name'])  # 존재X -> 에러 발생
print('a - ', a.get('name'))  # 존재X -> None 처리
a -  Kim
a -  Kim

👌 키, 값, (키, 값) 가져오기

print('a - ', list(a.keys()))
print('b - ', list(b.keys()))
print('c - ', list(c.keys()))
print('d - ', list(d.keys()))

print('a - ', list(a.values()))
print('b - ', list(b.values()))
print('c - ', list(c.values()))
print('d - ', list(d.values()))

print('a - ', list(a.items()))
print('b - ', list(b.items()))
print('c - ', list(c.items()))
print('d - ', list(d.items()))

print('a - ', a.pop('name'))
print('b - ', b.pop(0))
print('c - ', c.pop('arr'))
print('d - ', d.pop('City'))

print('f - ', f.popitem())  #키, 값 통째로 빼는거 (뒤에서부터)
print('f - ', f.popitem())
print('f - ', f.popitem())
print('f - ', f.popitem())
print('f - ', f.popitem())

꼭 값을 출력할 때, list()로 감싸서 출력해라

a -  ['name', 'phone', 'birth', 'address', 'rank']
b -  [0]
c -  ['arr']
d -  ['Name', 'City', 'Age', 'Grade', 'Status']

a -  ['Kim', '01012345678', '870124', 'seoul', [1, 2, 3]]
b -  ['Hello python!']
c -  [[1, 2, 3, 4]]
d -  ['Niceman', 'Seoul', '33', 'A', True]

a -  [('name', 'Kim'), ('phone', '01012345678'), ('birth', '870124'), ('address', 'seoul'), ('rank', [1, 2, 3])]
b -  [(0, 'Hello python!')]
c -  [('arr', [1, 2, 3, 4])]
d -  [('Name', 'Niceman'), ('City', 'Seoul'), ('Age', '33'), ('Grade', 'A'), ('Status', True)]

a -  Kim
b -  Hello python!
c -  [1, 2, 3, 4]
d -  Seoul

f -  ('Status', True)
f -  ('Grade', 'A')
f -  ('Age', '33')
f -  ('City', 'Seoul')
f -  ('Name', 'Niceman')

👌 요소 포함 여부 및 수정

# 포함 여부(키)
print('a - ', 'name' in a)
print('a - ', 'addr' in a)

# 수정
f.update(Age=36)
temp = {'Age': 27}
print('f - ', f)
f.update(temp)
print('f - ', f)
a -  False
a -  False

f -  {'Age': 36}
f -  {'Age': 27}

📌 Set

# 집합 자료형 활용
s1 = set([1, 2, 3, 4, 5, 6])
s2 = set([4, 5, 6, 7, 8, 9])

🎁 여러가지 집합 메서드

print('l - ', s1 & s2)
print('l - ', s1.intersection(s2))

print('l - ', s1 | s2)
print('l - ', s1.union(s2))

print('l - ', s1 - s2)
print('l - ', s1.difference(s2))

# 중복 원소 확인
print('l - ', s1.isdisjoint(s2)) #False는 중복원소가 있다는 뜻임

# 부분 집합 확인
print('l - ', s1.issubset(s2))  #False는 s2는 s1의 부분집합이 아님
print('l - ', s1.issuperset(s2)) #False는 s1이 s2를 포함하는 집합이 아님
l -  {4, 5, 6}
l -  {4, 5, 6}

l -  {1, 2, 3, 4, 5, 6, 7, 8, 9}
l -  {1, 2, 3, 4, 5, 6, 7, 8, 9}

l -  {1, 2, 3}
l -  {1, 2, 3}

l -  False

l -  False
l -  False

🎁 추가 및 제거

# 추가 & 제거
s1 = set([1, 2, 3, 4])
s1.add(5)
print('s1 - ', s1)

s1.remove(2)
print('s1 - ', s1)
# s1.remove(7)

s1.discard(3)
print('s1 - ', s1)

#s1.discard(7)  # 에러를 발생시키지 아니함

# 모두 제거
s1.clear()
s1 -  {1, 2, 3, 4, 5}
s1 -  {1, 3, 4, 5}
s1 -  {1, 4, 5}

📌 If, elif, else

🗂️ in, not in

e = {"name": 'Lee', "city": "Seoul", "grade": "A"}
r = (10, 12, 14)
print("name" in e)  # key 검색
print("seoul" in e.values())  # value 검색

📌 for

🔧 upper, isupper

name = 'FineApplE'

for n in name:
    if n.isupper():
        print(n)
    else:
        print(n.upper())
F
I
N
E
A
P
P
L
E

🔧 for else

# else 구문
numbers = [14, 3, 4, 7, 10, 24, 17, 2, 33, 15, 34, 36, 38]

for num in numbers:
    if num == 45:  # 45
        print("Found : 34!")
        break
else: # 반복문 다 돌아도 없으면 출력하는 조건문
    print("Not Found 45...")
Not Found 45...

📌 Function

⭐ *args, **kwargs

# 중요
# *args, **kwargs

# *args(언팩킹)
def args_func(*args): # 매개변수 명 자유
    for i, v in enumerate(args):
        print('Result : {}'.format(i), v)
    print('-----')
    

args_func('Lee')
args_func('Lee', 'Park')
args_func('Lee', 'Park', 'Kim')

# **kwargs(언팩킹)
def kwargs_func(**kwargs): # 매개변수 명 자유
    for v in kwargs.keys():
        print("{}".format(v), kwargs[v])
    print('-----')

kwargs_func(name1='Lee')
kwargs_func(name1='Lee', name2='Park')
kwargs_func(name1='Lee', name2='Park', name3='Cho')

# 전체 혼합
def example(args_1, args_2, *args, **kwargs):
    print(args_1, args_2, args, kwargs)

example(10, 20, 'Lee', 'Kim', 'Park', 'Cho', age1=20, age2=30, age3=40)
Result : 0 Lee
-----
Result : 0 Lee
Result : 1 Park
-----
Result : 0 Lee
Result : 1 Park
Result : 2 Kim
-----
name1 Lee
-----
name1 Lee
name2 Park
-----
name1 Lee
name2 Park
name3 Cho
-----
10 20 ('Lee', 'Kim', 'Park', 'Cho') {'age1': 20, 'age2': 30, 'age3': 40}

⭐ 중첩 함수

# 중첩함수

def nested_func(num):
    def func_in_func(num):
        print(num)
    print("In func")
    func_in_func(num + 100)

nested_func(100)

# 실행불가
# func_in_func(1000)
In func
200

⭐ lambda 함수

# 일반적함수 -> 할당
def mul_func(x, y):
    return x * y

print(mul_func(10, 50))

mul_func_var = mul_func
print(mul_func_var(20,50))

# 람다 함수 -> 할당
lambda_mul_func = lambda x,y:x*y
print(lambda_mul_func(50,50))

def func_final(x, y, func):
    print('>>>>', x * y * func(100, 100))

func_final(10, 20, lambda_mul_func)
500
1000
2500
>>>> 2000000

⭐ 함수 인자 기본타입 지정

# Hint
def tot_length1(word: str, num: int) -> int:
    return len(word) * num


print('hint exam1 : ', tot_length1("i love you", 10))


def tot_length2(word: str, num: int) -> None:
    print('hint exam2 : ', len(word) * num)


tot_length2("niceman", 10)
hint exam1 :  100
hint exam2 :  70

📌 객체지향

💯 클래스, 인스턴스, 네임스페이스

# 파이썬 클래스
# OOP(객체 지향 프로그래밍), Self, 인스턴스 메소드, 인스턴스 변수

# 클래스 and 인스턴스 차이 이해
# 네임스페이스 : 객체를 인스턴스화 할 때 저장된 공간
# 클래스 변수 : 직접 접근 가능, 공유
# 인스턴스 변수 : 객체마다 별도 존재

# 예제1
class Dog: # object 상속
    # 클래스 속성
    species = 'firstdog'
    
    # 초기화/인스턴스 속성
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
# 클래스 정보
print(Dog)

# 인스턴스화
a = Dog("mikky", 2)
b = Dog("baby", 3)

# 비교
print(a == b, id(a), id(b))

# 네임스페이스
print('dog1', a.__dict__)
print('dog2', b.__dict__)    
    
# 인스턴스 속성 확인
print('{} is {} and {} is {}'.format(a.name, a.age, b.name, b.age))

if a.species == 'firstdog':
    print('{0} is a {1}'.format(a.name, a.species))

print(Dog.species)
print(a.species)
print(b.species)
<class '__main__.Dog'>
False 1453702665360 1453702664080
dog1 {'name': 'mikky', 'age': 2}
dog2 {'name': 'baby', 'age': 3}
mikky is 2 and baby is 3
mikky is a firstdog
firstdog
firstdog
firstdog

💯 클래스 변수, 인스턴스 변수

# 예제3
# 클래스 변수, 인스턴스 변수
class Warehouse:
    # 클래스 변수 
    stock_num = 0 # 재고
    
    def __init__(self, name):
        # 인스턴스 변수
        self.name = name
        Warehouse.stock_num += 1
    
    def __del__(self):
        Warehouse.stock_num -= 1

user1 = Warehouse('Lee')
user2 = Warehouse('Cho')

print(Warehouse.stock_num)
# Warehouse.stock_num = 0.0094
print(user1.name)
print(user2.name)
print(user1.__dict__)
print(user2.__dict__)
print('before', Warehouse.__dict__)
print('>>>', user1.stock_num)

del user1
print('after', Warehouse.__dict__)
2
Lee
Cho
{'name': 'Lee'}
{'name': 'Cho'}
before {'__module__': '__main__', 'stock_num': 2, '__init__': <function Warehouse.__init__ at 0x00000152776DE020>, '__del__': <function Warehouse.__del__ at 0x00000152776DE0C0>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}
>>> 2
after {'__module__': '__main__', 'stock_num': 1, '__init__': <function Warehouse.__init__ at 0x00000152776DE020>, '__del__': <function Warehouse.__del__ at 0x00000152776DE0C0>, '__dict__': <attribute '__dict__' of 'Warehouse' objects>, '__weakref__': <attribute '__weakref__' of 'Warehouse' objects>, '__doc__': None}

💯 클래스, 인스턴스 복습

# 예제4
class Dog: # object 상속
    # 클래스 속성
    species = 'firstdog'
    
    # 초기화/인스턴스 속성
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def info(self):
        return '{} is {} years old'.format(self.name, self.age)
        
    def speak(self, sound):
        return "{} says {}!".format(self.name, sound)


# 인스턴스 생성
c = Dog('july', 4)
d = Dog('Marry', 10)
# 메소드 호출
print(c.info())
print(d.info())
# 메소드 호출
print(c.speak('Wal Wal'))
print(d.speak('Mung Mung'))
july is 4 years old
Marry is 10 years old
july says Wal Wal!
Marry says Mung Mung!

📌 Module

✔️ import 해서 사용하기

# 파이썬 모듈
# Module : 함수, 변수, 클래스 등 파이썬 구성 요소 등을 모아놓은 파일

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x , y):
    return x / y
    
def power(x, y):
    return x ** y
    
# __name__ 사용 : 여기서 실행해보고 다른 페이지에서 해당 페이지를 import 해서 사용하라는 것이다.
if __name__ == "__main__":
    print('-' * 15)
    print('called! __main__')
    print(add(5,5))
    print(subtract(15,5))
    print(multiply(5,5))
    print(divide(10,2))
    print(power(5,3))
    print('-' * 15)
import chapter06_02

print(chapter06_02.add(10, 10000))
10010

✔️package를 import해서 가져오기

import inspect
# from ..sub2 import module2

# module1.py
def mod1_test1():
	print ("Module1 -> Test1")
	print("Path : ", inspect.getfile(inspect.currentframe()))

def mod1_test2():
	print ("Module1 -> Test2")
	print("Path : ", inspect.getfile(inspect.currentframe()))
import inspect
# from ..sub1 import module1

# module2.py
def mod2_test1():
	print ("Module2 -> Test1")
	print("Path : ", inspect.getfile(inspect.currentframe()))

def mod2_test2():
	print ("Module2 -> Test2")
	print("Path : ", inspect.getfile(inspect.currentframe()))
# 예제1
import sub.sub1.module1
import sub.sub2.module2

# 사용
sub.sub1.module1.mod1_test1()
sub.sub1.module1.mod1_test2()

# 사용
sub.sub2.module2.mod2_test1()
sub.sub2.module2.mod2_test2()

print()
print()
print()

# 예제2
from sub.sub1 import module1
from sub.sub2 import module2 as m2 # Alias

# 사용
module1.mod1_test1()
module1.mod1_test2()

# 사용
m2.mod2_test1()
m2.mod2_test2()

print()
print()
print()

# 예제3
from sub.sub1 import *
from sub.sub2 import *

# 사용
module1.mod1_test1()
module1.mod1_test2()

# 사용
module2.mod2_test1()
module2.mod2_test2()

print()
print()
print()

📌 예외처리

# try:
#     z = 'Cho' # 'Cho'
#     x = name.index(z)
#     print('{} Found it! {} in name'.format(z, x + 1))
# except Exception as e:
#     print(e)
#     print('Not found it! - Occurred ValueError!')
# else: # 에러가 없으면 마지막으로 실행됨
#     print('Ok! else.')
# finally: # 에러가 있든 없든 마지막에 무조건 실행됨.
#     print('Ok! finally')

📌 내장함수

✏️ zip

# zip : 반복가능한 객체(Iterable)의 요소를 묶어서 반환

print(list(zip([10,20,30],[40,50,777])))
print(type(list(zip([10,20,30],[40,50,777]))[0]))
[(10, 40), (20, 50), (30, 777)]
<class 'tuple'>

✏️ round

# round : 반올림

print(round(6.5781, 2))     # 6.58
print(round(5.6))			# 6

✏️ map

# map : 반복가능한 객체 요소를 지정한 함수 실행 후 추출
def conv_abs(x):
    return abs(x)
    
print(list(map(conv_abs,[1,-3,2,0,-5,6])))
print(list(map(lambda x:abs(x),[1,-3,2,0,-5,6])))
[1, 3, 2, 0, 5, 6]
[1, 3, 2, 0, 5, 6]

✏️ filter

#  filter : 반복가능한 객체 요소를 지정한 함수 조건에 맞는 값 추출

def conv_pos(x):
    return abs(x) > 2
    
print(list(filter(conv_pos, [1, -3, 2, 0, -5, 6])))
print(list(filter(lambda x: abs(x) > 2, [1, -3, 2, 0, -5, 6])))
[-3, -5, 6]
[-3, -5, 6]

✏️ enumerate

# enumerate : 인덱스 + Iterable 객체 생성
for i, name in enumerate(['abc', 'bcd', 'efg']):
    print(i, name)
0 abc
1 bcd
2 efg

✏️ all, any

# all, any : iterable 요소 검사(참, 거짓)
	print(all([1,2,3])) # and
    # True
	print(any([1,2,0])) # or
    True

✏️ chr(숫자), ord(문자)

# chr : 아스키 -> 문자 , ord : 문자 -> 아스키
	print(chr(67))   #C
	print(ord('C'))  #67
profile
필요하다면 공부하는 개발자, 한승준

0개의 댓글