[Python] 컴프리핸션, if문, for문, while문

seonyoung·2024년 7월 30일
0

📁 캠프리핸션

  • 파이썬 코드를 fancy 하게 짜는 것

<기본 리스트 생성 방법>

# 기존 방식
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for number in numbers:
    squared_numbers.append(number ** 2)

print(squared_numbers)  # [1, 4, 9, 16, 25]

<리스트 컴프리핸션 사용>

# 리스트 컴프리핸션 사용
numbers = [1, 2, 3, 4, 5]
squared_numbers = [number ** 2 for number in numbers]

print(squared_numbers)  # [1, 4, 9, 16, 25]

<기본 딕셔너리 생성 방법>

# 기존 방식
numbers = [1, 2, 3, 4, 5]
squared_dict = {}
for number in numbers:
    squared_dict[number] = number ** 2

print(squared_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

<딕셔너리 컴프리핸션 사용>

# 딕셔너리 컴프리핸션 사용
numbers = [1, 2, 3, 4, 5]
squared_dict = {number: number ** 2 for number in numbers}

print(squared_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

<장점>

  • 코드가 간결해짐
  • 리스트를 만드는 과정이 한 눈에 들어옴
  • 더 빠른 실행 속도를 가질 수 있음

<단점>

  • 복잡한 로직을 포함할 경우 가독성이 떨어질 수 있음
  • 너무 긴 컴프리핸션은 코드의 이해를 어렵게 만들 수 있음
  • ex)
# 리스트 컴프리핸션을 사용하지 않을 경우
names = ["Alice", "Bob", "Charlie"]
uppercase_names = []
for name in names:
    uppercase_names.append(name.upper())

print(uppercase_names)  # ['ALICE', 'BOB', 'CHARLIE']

# 리스트 컴프리핸션을 사용할 경우
uppercase_names = [name.upper() for name in names]
print(uppercase_names)  # ['ALICE', 'BOB', 'CHARLIE']

# 딕셔너리 컴프리핸션을 사용하지 않을 경우
names = ["Alice", "Bob", "Charlie"]
name_length_dict = {}
for name in names:
    name_length_dict[name] = len(name)

print(name_length_dict)  # {'Alice': 5, 'Bob': 3, 'Charlie': 7}

# 딕셔너리 컴프리핸션을 사용할 경우
name_length_dict = {name: len(name) for name in names}
print(name_length_dict)  # {'Alice': 5, 'Bob': 3, 'Charlie': 7}

📁 if문

<if 문 기본 구조>

money = True
if money:
	print("택시를 타고 가라")
else:
	print("걸어 가라")

<비교 연산자>

비교연산자설명
x < yx가 y보다 작다
x > yx가 y보다 크다
x == yx와 y가 같다
x != yx와 y가 같지 않다
x >= yx가 y보다 크거나 같다
x <= yx가 y보다 작거나 같다
money = 2000
if money>=3000:
    print("택시를 타고 가라")
else:
    print("걸어가라")

< and or not >

연산자설명
x or yx와 y 둘 중 하나만 참이어도 참
x and yx와 y 모두 참이어야 참
not xx가 거짓이면 참
money = 2000
card = True
if money>=3000 or card:
    print("택시를 타고 가라")
else:
    print("걸어가라")

< in not in >

innot in
x in 리스트x not in 리스트
x in 튜플x not in 튜플
x in 문자열x not in 문자열
1 in [1, 2, 3]
1 not in [1, 2, 3]
pocket = ['paper', 'cellphone', 'money']
if 'money' in pocket:
	print("택시를 타고 가라")
else:
	print("걸어가라")

<다양한 조건은 elif>

pocket = ['paper', 'cellphone']
card = True
if 'money' in pocket:
      print("택시를 타고가라")
elif card: 
      print("택시를 타고가라")
else:
      print("걸어가라")
money = 5000

if money<=3000:
    print("걸어가라")
elif money<=4000:
    print("버스타라")
elif money<=10000:
    print("택시타라")
else:
    print("비행기 타라")

<if 문을 패스 하고 싶으면?>

pocket = ['paper', 'money', 'cellphone']
if 'money' in pocket:
    pass 
else:
    print("카드를 꺼내라")

📁 for문

<for 문 기본 구조>

for 변수 in 리스트(또는 튜플, 문자열):
    수행할_문장1
    수행할_문장2

<리스트를 활용한 for문>

test_list = ['one', 'two', 'three'] 
for i in test_list:
    print(i)
# 연습문제
marks = [90, 25, 67, 45, 80]   # 학생들의 시험 점수 리스트

number = 0   # 학생에게 붙여 줄 번호
for mark in marks:   # 90, 25, 67, 45, 80을 순서대로 mark에 대입
    number = number +1 
    if mark >= 60: 
        print("%d번 학생은 합격입니다." % number)
    else: 
        print("%d번 학생은 불합격입니다." % number)

<range를 활용한 for문>

  • for 문은 숫자 리스트를 자동으로 만들어 주는 range 함수와 함께 사용하는 경우가 많다. 다음은 range 함수의 간단한 사용법
a = range(10)
a
for i in range(1,10):
    print(i)
for i in range(1,10,2):
    print(i)

add = 0 
for i in range(1, 11): 
    add = add + i 

print(add)

< for문과 continue>

  • for 문 안의 문장을 수행하는 도중 continue 문을 만나면 for 문의 처음으로 돌아가게 됨
marks = [90, 25, 67, 45, 80]

number = 0 
for mark in marks: 
    number = number +1 
    if mark < 60:
        continue 
    print("%d번 학생 축하합니다. 합격입니다. " % number)

📁 while문

<while 문 기본 구조>

  • while 문은 조건문이 참이면 계속해서 반복실행
while 조건문:
    수행할_문장1
    수행할_문장2
    수행할_문장3
treeHit = 0
while treeHit < 10:
    treeHit = treeHit +1
    print("나무를 %d번 찍었습니다." % treeHit)
    if treeHit == 10:
        print("나무 넘어갑니다.")

<while문 강제로 빠져나가기 → break>
ex) 커피 자판기

coffee = 10
money = 300
while money:
    print("돈을 받았으니 커피를 줍니다.")
    coffee = coffee -1
    print("남은 커피의 양은 %d개입니다." % coffee)
    if coffee == 0:
        print("커피가 다 떨어졌습니다. 판매를 중지합니다.")
        break

<while 문과 continue>

a = 0
while a < 10:
    a = a + 1
    if a % 2 == 0: continue
    print(a)
profile
원하는 바를 이루고 싶은 사람입니다.

0개의 댓글