1.1 If 문 #Writing Idiomatic Python 3.1

oen·2022년 1월 5일
0

1. 비교할 때는 연결해서 사용하자

👎

if x <= y and y <= z:
	return True

👍

if x <= y <= z:
	return True

2. 한 줄로 쓰지 말자

👎

if True: print('bad')

👍

if True:
	print('good')

3. 변수 이름을 중복으로 사용하지 말자

👎

is_generic_name = False
name = 'person1'
if name == 'person1' or name == 'person2' or name == 'person3':
	is_generic_name = True

👍

name = 'person1'
is_generic_name = name in ('person1', 'person2', 'person3')

4. (꼭 필요한 경우를 제외하곤) True, False, None과 직접 비교하지 말자

👎

foo = True
if foo == True:
	print('not implicit')

👍

foo = True
if foo:
	print('implicit')

✔️ 예외

def insert_value(value, position=None):
	if position is not None:
    	...

만약 if position:으로 하게 되면 position에 0이 들어왔을 때 값이 들어왔음에도 불구하고 if position은 False가 되기 때문에 문제가 생긴다. 이렇게 None과 비교해야 할 때는 직접 비교해야 한다.

5. (코드가 심플한 경우엔) if, else는 삼항연산자를 쓰자

파이썬은 삼항 연산자(x ? True : False)는 없지만, 아래와 같이 사용할 수 있다.

👎

foo = True
value = 0

if foo:
	value = 1

👍

foo = True

value = 1 if foo else 0

⚠️

코드가 복잡한 경우에는 오히려 헷갈릴 수 있으니 간단한 코드에서만 사용하자.

profile
🐾

0개의 댓글