[SK shieldus Rookies 19기] 인프라 활용을 위한 파이썬 3일차

기록하는짱구·2024년 3월 4일
0

SK Shieldus Rookies 19기

목록 보기
3/43
post-thumbnail

📌 실습 #1

세 개의 변수 x, y, z 중 가장 큰 수를 출력하는 프로그램을 작성하시오. (내장 함수를 이용하지 않고 작성)

a = int(input("첫번째 숫자: "))
b = int(input("두번째 숫자: "))
c = int(input("세번째 숫자: "))

# max 함수와 같은 기능을 하는 코드를 작성
x = max(a, b, c)    

print(f"가장 큰 수는 {x}입니다.")





a = int(input("첫번째 숫자: "))
b = int(input("두번째 숫자: "))
c = int(input("세번째 숫자: "))

# max 함수와 같은 기능을 하는 코드를 작성
# x = max(a, b, c)    
if a > b and a > c:
    x = a
elif a > b and a < c:
    x = c
elif a < b and b > c:
    x = b
elif a < b and b < c:
    x = c

print(f"가장 큰 수는 {x}입니다.")





a = int(input("첫번째 숫자: "))
b = int(input("두번째 숫자: "))
c = int(input("세번째 숫자: "))


# max 함수와 같은 기능을 하는 코드를 작성
# x = max(a, b, c)    


x = (a if a > b else b) if a > c else (b if b > c else c)


print(f"가장 큰 수는 {x}입니다.")

📌 실습 #2

세 개의 변수 x, y, z를 조사해서 가장 큰 홀수를 출력하는 프로그램을 작성하시오. 이 중에 홀수가 없다면 셋 중에 가장 작은 값을 출력해야 합니다.

<답안>

a = int(input('첫번째 수: '))
b = int(input('두번째 수: '))
c = int(input('세번째 수: '))

ans = min(a, b, c)

if a % 2 != 0:
    ans = a

if b % 2 != 0 and b > ans:
    ans = b

if c % 2 != 0 and c > ans:
    ans = c

print(ans)


a = int(input('첫번째 수: '))
b = int(input('두번째 수: '))
c = int(input('세번째 수: '))

numbers = [ a, b, c ]
numbers.sort(reverse=True)

ans = 0
for no in numbers:
    if no % 2 != 0:
        ans = no
        break

if ans == 0:
    ans = min(numbers)

print(ans)


a = int(input('첫번째 수: '))
b = int(input('두번째 수: '))
c = int(input('세번째 수: '))

numbers = [ a, b, c ]

odd_numbers = [ no for no in numbers if no % 2 != 0 ]

if odd_numbers:
    print(max(odd_numbers))
else:
    print(min(numbers))


a = int(input('첫번째 수: '))
b = int(input('두번째 수: '))
c = int(input('세번째 수: '))

numbers = [ a, b, c ]

def odd(no):
    return no % 2 != 0

odd_numbers = list(filter(odd, numbers))  # filter 함수 사용

if odd_numbers:
    print(max(odd_numbers))
else:
    print(min(numbers))
    
    
def odd(no):
    return no % 2 != 0
   
numbers = []
while True:
    a = input('숫자를 입력하세요. 끝낼려면 q를 입력하세요.: ')
    if a == 'q':
        break
   
    numbers.append(int(a))

odd_numbers = list(filter(odd, numbers))

if odd_numbers:
    print(max(odd_numbers))
else:
    print(min(numbers))

📌 while문

📝 while 문

TrueFalse로 나뉘는 분기문
문장을 반복 수행하는 반복문

while 조건문:  # 조건문이 참인 동안 문장들 반복 수행
   	수행할 문장1
    수행할 문장2
    수행할 문장3

📝 break

while 문 강제로 빠져나가기

n = 0
m = 0
while True:
    n += 1
    print(f"#1 >>> ({n}, {m})")

    while True:
        m += 1
        print(f"#2 >>> ({n}, {m})")
        if m > 3: break				#### 1
        print(f"#3 >>> ({n}, {m})")

    if n > 3: break				    #### 2
    print(f"#4 >>> ({n}, {m})")



#1 >>> (1, 0)
#2 >>> (1, 1)
#3 >>> (1, 1)
#2 >>> (1, 2)
#3 >>> (1, 2)
#2 >>> (1, 3)
#3 >>> (1, 3)
#2 >>> (1, 4)			# #### 1 코드가 작동 → 내부의 while 루프를 빠져나옴
#4 >>> (1, 4)
#1 >>> (2, 4)
#2 >>> (2, 5)
#4 >>> (2, 5)
#1 >>> (3, 5)
#2 >>> (3, 6)
#4 >>> (3, 6)
#1 >>> (4, 6)
#2 >>> (4, 7)			# #### 2 코드가 작동 → 외부의 while 루프를 빠져나옴

📝 continue

while 문의 맨 처음으로 돌아가기

📌 for문

📝 for 문

리스트나 튜플, 문자열의 첫 번째 요소부터 마지막 요소까지 차례로 변수에 대입되어 수행할 문장들이 수행

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

📝 for 문의 형태

일반적인 for 문

>>> test_list = ['one', 'two', 'three']  # 리스트의 첫 번째 요소인 'one'이
                                           i 변수에 대입된 후 print 문장 수행
                                           두 번째 요소, 세 번째 요소까지 반복
>>> for i in test_list: 
...     print(i)
... 
one 
two 
three

다양한 for 문

>>> a = [(1,2), (3,4), (5,6)]
>>> for (first, last) in a:  # 리스트의 요솟값이 튜플이므로
						     # 각각의 요소가 자동으로 (first, last) 변수에 대입
...     print(first + last)
...
3
7
11

for 문의 응용

# 시험 점수가 60점 이상이면 합격이고 그렇지 않으면 불합격
# 합격인지, 불합격인지 결과 출력

marks = [90, 25, 67, 45, 80]   # 학생들의 시험 점수 리스트

number = 0   # 학생에게 붙여 줄 번호
for mark in marks:  # marks에서 차례로 점수를 꺼내어 mark라는 변수에 대입
    number = number +1   # for 문이 한 번씩 수행될 때마다 number는 1씩 증가
    if mark >= 60: 
        print("%d번 학생은 합격입니다." % number)
    else: 
        print("%d번 학생은 불합격입니다." % number)

💡 for 문과 자주 사용되는 range 함수
range(시작 숫자, 끝 숫자) 형태
→ 이때, 끝 숫자는 포함 X

for i in range(10):
    print(i, end=" ")			# 0 1 2 3 4 5 6 7 8 9
print()
for i in range(1, 10):
    print(i, end=" ")    		# 1 2 3 4 5 6 7 8 9
    print()
for i in range(1, 10, 2):
    print(i, end=" ")			# 1 3 5 7 9

📝 리스트의 인덱스와 값 출력

scores = [ 10, 22, 30, 44, 50, 66 ]


# range(len(리스트 변수)) 방법
for index in range(len(scores)):
    print(f'{index+1}번째 학생의 점수는 {scores[index]}점입니다.')


# enumerate() 함수 이용하는 방법
scoresWithIndex = list(enumerate(scores))
for index, score in scoresWithIndex:
    print(f'{index+1}번째 학생의 점수는 {score}점입니다.')

💡 enumerate
(인덱스, 값) 형식의 튜플 리스트 반환 리스트 데이터를 튜플로 반환해주는 함수

📝 구구단

for dan in range(2, 10):
    print(f'{dan}단')
    for no in range(1, 10):
        print(f'{dan} x {no} = {dan*no:2}')
        
결과
234567892 x 1 =  2   3 x 1 =  3   4 x 1 =  4   5 x 1 =  5   6 x 1 =  6   7 x 1 =  7   8 x 1 =  8   9 x 1 =  9
2 x 2 =  4   3 x 2 =  6   4 x 2 =  8   5 x 2 = 10   6 x 2 = 12   7 x 2 = 14   8 x 2 = 16   9 x 2 = 18
2 x 3 =  6   3 x 3 =  9   4 x 3 = 12   5 x 3 = 15   6 x 3 = 18   7 x 3 = 21   8 x 3 = 24   9 x 3 = 27
2 x 4 =  8   3 x 4 = 12   4 x 4 = 16   5 x 4 = 20   6 x 4 = 24   7 x 4 = 28   8 x 4 = 32   9 x 4 = 36
2 x 5 = 10   3 x 5 = 15   4 x 5 = 20   5 x 5 = 25   6 x 5 = 30   7 x 5 = 35   8 x 5 = 40   9 x 5 = 45
2 x 6 = 12   3 x 6 = 18   4 x 6 = 24   5 x 6 = 30   6 x 6 = 36   7 x 6 = 42   8 x 6 = 48   9 x 6 = 54   
2 x 7 = 14   3 x 7 = 21   4 x 7 = 28   5 x 7 = 35   6 x 7 = 42   7 x 7 = 49   8 x 7 = 56   9 x 7 = 63
2 x 8 = 16   3 x 8 = 24   4 x 8 = 32   5 x 8 = 40   6 x 8 = 48   7 x 8 = 56   8 x 8 = 64   9 x 8 = 72
2 x 9 = 18   3 x 9 = 27   4 x 9 = 36   5 x 9 = 45   6 x 9 = 54   7 x 9 = 63   8 x 9 = 72   9 x 9 = 81


for no in range(0, 10):
    for dan in range(2, 10):
        if no == 0:
            print(f'{dan}단', end=' '*10)
        else:
            print(f'{dan} x {no} = {dan*no:2}', end=' '*3)
    print()

📝 리스트 컴프리헨션(list comprehension)

리스트 안에 for 문을 포함하는 리스트 컴프리헨션(list comprehension)을 사용하면 좀 더 편리하고 직관적인 프로그램을 만들 수 있음

💡 형태
[표현식 for 항목 in 반복 가능 객체 if 조건문]
ex. [num * 3 for num in a if num % 2 == 0]

📌 Map & Filter

📖 map

첫 번째 매개변수로 함수가 오고 두 번째 매개변수로 반복 가능한 자료형(리스트, 튜플 등)이 옴

map 함수의 반환 값은 map 객체이기 때문에 해당 자료형을 list 혹은 tuple로 형 변환

💡 형태
map(function, iterable)
→ map(적용시킬 함수, 적용할 값들)

📖 filter

함수에 대해 True를 반환하는 값을 필터링해주는 기능

첫 번째 매개변수로 필터링을 적용시킬 함수가 오고 두 번째 매개변수로 반복 가능한 값들이 들어오게 됨

filter 함수는 iterator에 들어온 값들을 하나하나 function에 넣어서 반환이 true인 값을 필터링해서 다시 리스트로 만들어주는 함수

💡 형태
filter(function, iterator)

numbers = [ 1, 2, 3, 4, 5, 6 ]

# append() 함수를 이용
results = []
for num in numbers:
    results.append(num * 3)

print(results)


# list comprehension 표기법을 이용
results2 = [ num * 3 for num in numbers ]
print(results2)


# map() 함수를 이용하는 방법
def threeTimes(num):
    return num * 3

results3 = list(map(threeTimes, numbers))
print(results3)



numbers = [ 1, 2, 3, 4, 5, 6 ]

# append() 함수를 이용
results = []
for num in numbers:
    if num % 2 != 0:
        results.append(num * 3)

print(results)


# list comprehension 표기법을 이용
results2 = [ num * 3 for num in numbers if num % 2 != 0 ]
print(results2)


# map() 함수를 이용하는 방법
def oddNumbers(num):
    return num % 2 != 0

def threeTimes(num):
    return num * 3

results3 = list(map(threeTimes, filter(oddNumbers, numbers)))
print(results3)

📌 실습 #3

두 수를 입력 받아서 최대 공약수를 출력하는 프로그램을 작성해보세요.

Ex)
첫번째 수: 24
두번째 수: 16
24와 16의 최대 공약수: 8

# 두 수를 입력 받아서 최대 공약수를 출력하는 프로그램을 작성해 보세요.
# 예)
# 첫번째 수: 24
# 두번째 수: 16
# 24와 16의 최대 공약수: 8


a = int(input('첫번째 수: '))
b = int(input('두번째 수: '))


if a > b:
    a, b = b, a     # 첫번째 수를 작은 수로, 두번째 수를 큰 수로 설정


for i in range(a, 0, -1):
    if a % i == 0 and b % i == 0:   	# 공약수
        print(f'{a}{b}의 최대 공약수: {i}')
        break				# 최대 공약수를 구했으므로 더 이상 반복하지 않음

📌 실습 #4

몸무게 정보를 담고 있는 리스트에서 몸무게가 80 이상이면 비만, 아니면 정상을 출력하는 results 리스트 작성

Ex)
[20, 70, 87, 99, 82, 60]

['정상', '정상', '비만', '비만', '비만', '정상']

빈 리스트에 append() 함수를 이용해 조건에 따른 데이터 추가

weights = [20, 70, 87, 99, 82, 60]

results = []
for w in weights:
    if w >= 80:
        results.append('비만')
    else:
        results.append('정상')

print(weights)        
print(results)

map() 함수 이용

weights = [20, 70, 87, 99, 82, 60]

def checkWeights(w):
    if w >= 80: return '비만'
    else:
    return '정상'


results = list(map(checkWeights, weights))

print(weights)        
print(results)

📌 실습 #5

위의 코드를 '몸무게 : 정상여부' 형식으로 출력하도록 수정

Ex)
20 : 정상
80 : 비만

range(len(리스트)) 함수를 이용해 인덱스를 가져와 출력

weights = [20, 70, 87, 99, 82, 60]

results = ["정상" if weight < 80 else "비만" for weight in weights]

for i in range(len(weights)):
    print(f"{weights[i]} : {results[i]}")

enumerate() 함수를 이용하는 방법

weights = [20, 70, 87, 99, 82, 60]

results = ["정상" if weight < 80 else "비만" for weight in weights]

for index, weight in enumerate(weights):
    print(f"{weight} : {results[index]}")

zip() 함수를 이용하는 방법

weights = [20, 70, 87, 99, 82, 60]

results = ["정상" if weight < 80 else "비만" for weight in weights]

for weight, result in zip(weights, results):
    print(f"{weight} : {result}")

📌 *args & **kwargs

📖 *args

콤마로 구분한 여러 개의 인자(= positional argument)를 튜플로 반환

📖 **kwargs

이름과 값으로 구성된 여러 개의 인자(= keyword argument)를 딕셔너리로 반환

📱 계산기

 def calcurator(operator, *operand):
    if operator == "+":
       result = 0
        for i in operand:
            result += i

        return result
   
    if operator == "*":
        result = 1
        for i in operand:
            result *= i
           
        return result
def calcurator2(**kwargs):
    return calcurator(kwargs["operator"], *kwargs["operand"])

print(calcurator("*", 10, 20, 30))
print(calcurator("+", 10, 20, 30))

print(calcurator2(operator="*", operand=(10, 20, 30)))
print(calcurator2(operator="+", operand=(10, 20, 30)))

📌 내장 함수 사용법 확인

help(function_name)

>> help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.


>>> help(enumerate)
Help on class enumerate in module builtins:

class enumerate(object)
 |  enumerate(iterable, start=0)
 |
 |  Return an enumerate object.
 |
 |    iterable
 |      an object supporting iteration
 |
 |  The enumerate object yields pairs containing a count (from start, which
 |  defaults to zero) and a value yielded by the iterable argument.
-- More  --

>>> def add(a, b):			# 함수 헤더 → 함수이름(매개변수)
...     return a + b		# 함수 본문 → 들여쓰기로 구분
...

>>> help(add)
Help on function add in module __main__:

add(a, b)					# 함수 헤더가 출력

📌 지역변수 & 전역변수

지역변수

함수를 호출할 때마다 생성되며 함수가 반환될 때 제거

전역변수

지역 변수와 달리, 이 변수가 선언된 이 후에 정의되는 모든 함수에서 별도의 선언 없이 사용

📌 난수(random number)

import random

for i in range(0, 10):
    #print(random.random())         # 0 < random.random() < 1 실수

    r = int(random.random() * 100)  # 0 < r < 100 정수
    print(r)

print()
for i in range(0, 10):
    r = random.randrange(1, 7)      # 1 <= r < 7 정수    
    print(r)

📌 실습 #6

숫자 맞추기

  1. 프로그램에서 생성한 0보다 크고, 100 보다 작은 임의의 난수를 맞추는 게임

  2. 사용자가 숫자를 입력하면 메시지를 출력
    생성한 숫자 보다 크면 "크다"
    생성한 숫자 보다 작으면 "작다"
    생성한 숫자와 입력한 숫자가 일치하면 "00번만에 맞췄습니다."

  3. 사용자가 숫자를 입력하는 기회는 10번으로 제한
    남은 기회를 출력
    모든 기회가 사용되면 프로그램을 종료

import random


target = random.randint(1, 99)

count = 0

print("숫자 맞추기 게임을 시작합니다.")

while True:
    count += 1
    num = int(input("1 ~ 99 사이의 숫자를 입력하시오."))
    if num == target:
        print(f"정답입니다. {count}번 만에 맞추셨습니다.")
        break
    elif num > target:
        print("입력한 숫자가 정답 보다 큽니다.")
    else:
        print("입력한 숫자가 정답 보다 작습니다.")

    if count == 10:
        print(f"모든 기회를 소진하였습니다. 정답은 {target} 입니다.")        
        break
    else:
        print(f'{10-count} 기회가 남았습니다.')

📌 실습 #7

행맨

  1. 사용자로부터 영어 문장을 입력 받음
  2. 입력받은 문장을 구성하고 있는 임의의 단어를 하나 추출해서, 해당 단어를 맞추는 게임
  3. 단어의 길이 만큼 "_"를 출력 → 단어: _
  4. 사용자가 알파벳을 입력하면 해당 위치에 알파벳을 출력 → t를 입력 _t__t
  5. 단어를 맞추는 횟수는 10번으로 제한
  6. 주어진 횟수 안에 단어를 맞추면 단어와 시도 횟수를 출력

import re


words = input('여러 단어로 구성된 문장을 입력하세요. ')
print(f"입력 : {words}")


# 문장부호를 제거 ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~ \
words = re.sub(r'[!"#$%&\'()*+,-./:;<=>?@\[\]^_\`{|}~\\\\]', '', words)
for word in words.split():
    print(word)



import re
import random


# words = input('여러 단어로 구성된 문장을 입력하세요. ')
words = "Visit BBC for trusted reporting on the latest world and US news, sports, business, climate, innovation, culture and much more."
print(f"입력 : {words}")


# 문장부호를 제거 ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~ \
words = re.sub(r'[!"#$%&\'()*+,-./:;<=>?@\[\]^_\`{|}~\\\\]', '', words)


# 공백문자를 기준으로 단어를 분리
words = words.split()


# 임의의 단어를 추출
rand_word = list(words[random.randrange(len(words))])


# 화면에 출력할 내용
disp_word = list('_' * len(rand_word))
print(f'힌트 >>> {''.join(disp_word)}')

try_count = 0
while True:
    try_count += 1
    alpha = input(f'{try_count} 시도 >>> 영어 단어를 구성하는 알파벳을 입력하세요. ')

    for i, a in enumerate(rand_word):
        if alpha == a:
            disp_word[i] = alpha
    print(f'힌트 >>> {''.join(disp_word)}')

    if disp_word.count('_') == 0:
        print(f'정답 "{''.join(rand_word)}"를 {try_count}번 만에 맞췄습니다.')
        break
    elif try_count >= 10:
        print(f'10번에 기회가 모두 끝났습니다. 정답은 "{''.join(rand_word)}" 입니다.')
        break

zip

동일한 두 개의 리스트를 하나의 값으로 결합시키는 역할
튜플 형식으로 출력

📌 함수

프로그램의 구조

① 순차적으로 실행되는 구조
② 조건에 따라 동작이 달라지는 구조(분기문)
③ 일정한 조건을 만족하는 동안에 특정 조건이 반복되는 구조(반복문)

함수

호출해서 실행
def 라는 예약어로 정의

def 함수 이름(매개변수):  # 함수 헤더
	수행 문장1  # 함수 본문
	수행 문장2

실행결과 반환 시 return이라는 키워드 사용

def add(a, b):
	return a+b

📢 여기서 잠깐! 매개변수(parameter)와 인수(arguments)는 혼용해서 사용

매개변수와 인수의 차이점

매개변수는 함수에 입력으로 전달된 값을 받는 '변수',
인수는 함수를 호출할 때 전달하는 입력 ''

def add(a, b):  # a, b는 매개변수
	return a+b

print(add(3, 4))  # 3, 4는 인수

함수는 반복되는 행위들을 정의해놓은 코드

정의된 코드는 입력값에 의해 동작이 결정
동작의 결과는 호출한 쪽에 의해 리턴값으로 반환
함수의 리턴값은 언제나 하나

리턴값이 있다? 없다?

함수의 형태는 입력값과 리턴값의 존재 유무에 따라 유형이 나뉨

① 입력값이 없는 함수
say를 호출하면 Hi가 출력

>>> def say():
	return 'Hi'

② 리턴값이 없는 함수
리턴값이 없으면 자동으로 None 리턴

③ 매개변수를 지정하여 호출
매개변수를 지정하면 순서에 상관없이 사용할 수 있음

입력값이 몇 개인지 모를 땐 *args 사용

args는 인수를 뜻하는 영단어 arguments의 약자
하나만 사용하면 값을 나열해서 사용

키워드 매개변수, kargs

Key=Value 형태의 입력값
**kwargs 형태
매개변수에는 초깃값을 미리 설정

return의 또 다른 쓰임새

함수를 단독으로 사용해 함수를 즉시 빠져나갈 때도 쓰임
return이 없어도 리턴값 리턴 가능

함수 안에서 선언한 변수의 효력 범위

global 명령어 사용
그러나 전역 변수는 로직이 꼬일 수 있으므로 되도록 사용 X

lambda 예약어
def를 사용할 정도로 복잡하지 않거나 def를 사용하지 못하는 곳에 주로 쓰임

💡 형태
함수 이름 = lambda 매개변수1, 매개변수2 : 매개변수를 이용한 표현식

📌 파일 읽고 쓰기

입출력 방법이 사용자가 직접 입력하고 모니터 화면에 입력값을 출력하는 방식만 있는 것은 아님
→ 파일을 통한 입출력 방법도 있음

파일 생성

파일을 생성하기 위해 내장 함수 open 사용

💡 형태
파일 객체 = open(파일 이름, 파일 열기 모드)

파일 열기 모드

r 읽기 모드
읽을 때만 사용

w 쓰기 모드
파일에 내용을 쓸 때 사용

a 추가 모드

open 을 통해 열려있는 파일은 그대로 두면 에러가 발생할 확률이 높으므로 close 를 사용해 닫기를 추천

파일 경로와 슬래시(/)

파일 경로
슬래시 / 사용

"C:/doit/새파일. txt"

역슬래시 \ 사용

파일 쓰기

wirte

# w 모드 및 a 모드인 경우 파일이 존재하지 않는 경우 파일을 생성한 후 오픈
# r 모드인 경우 파일이 존재하지 않으면 FileNotFound 오류가 발생
f = open(r'new_file.txt', 'w', encoding='utf-8')  


for i in range(1, 11):
    # 줄 바꿈을 위해서는 개행문자(\n)을 추가해야 함
    f.write(f'{i}번째 라인\n')

파일 읽기

readline
행 단위로 파일 읽기

f = open(r'new_file.txt', 'r', encoding='utf-8')  

while True:
    line = f.readline()
    if not line:
        break
    print(line, end='')

f.close()

readlines
파일 내용을 행 단위로 읽어서 리스트로 반환

f = open(r'new_file.txt', 'r', encoding='utf-8')  


# for i in range(1, 10):
#     f.write(f'{i}번째 라인입니다.\n')


# 파일 내용을 줄 단위로 저장하고 있는 리스트 반환
lines = f.readlines()
print(lines)        
   
for line in lines:
    print(line, end="")


f.close()

0개의 댓글