Data Scientist 옌

매일 발전하는 IT문제해결사

Programing 프로그래밍/Python 파이썬

[나도코딩] Python 코딩 무료 강의 (기본편) 정리 (2/3)

옌炎 2022. 1. 14. 12:12
728x90

<파이썬 코딩 무료 강의 (기본편) - 6시간 뒤면 여러분도 개발자가 될 수 있어요 [나도코딩]>을 보면서 정리한 내용입니다.

분기

1. If문

weather = input("오늘 날씨는 어때요?")

if weather == "비" or weather == "눈":
    print("우산을 챙기세요")
elif weather == "미세먼지":
    print("마스크를 챙기세요")
else:
    print("준비물 필요 없어요")

temp = int(input("기온은 어때요?"))

if 30 <= temp:
    print("너무 더워요. 나가지 마세요")
elif 10 <= temp and temp < 30:
    print("괜찮은 날씨에요")
elif 0 <= temp < 10:
    print("외투를 챙기세요")
else:
    print("너무 추워요. 나가지 마세요")

2. For문 

# print("대기번호 : 1")
# print("대기번호 : 2")
# print("대기번호 : 3")
# print("대기번호 : 4")

for waiting_no in range(1, 6):
    print("대기번호 : {0}".format(waiting_no))

starbucks = ["아이언맨", "토르", "아이엠 그루트"]

for customer in starbucks:
    print("{0}, 커피가 준비되었습니다.".format(customer))

3. While문

customer = "토르"
index = 5

while index >= 1:
    print("{0}, 커피가 준비되었습니다. {1} 번 남았어요.".format(customer, index))
    index -= 1
    if index == 0:
        print("커피는 폐기처분되었습니다.")

customer = "아이언맨"
index = 1
while True:
    print("{0}, 커피가 준비되었습니다. 호출 {1} 회".format(customer, index))
    index += 1


customer = "토르"
person = "Unknown"

while person != customer:
    print("{0}, 커피가 준비되었습니다.".format(customer))
    person = input("이름이 어떻게 되세요?")

4. Continue와 Break

absent = [2, 5] # 결석
no_book = [7] # 책을 깜박했음

for student in range(1, 11):
    if student in absent:
        continue
    elif student in no_book:
        print("오늘 수업 여기까지. {0}는 교무실로 따라와".format(student))
        break
    print("{0}, 책을 읽어봐".format(student))

5. 한 줄 for

# 출석번호가 1 2 3 4, 앞에 100을 붙이기로 함 -> 101, 102, 103, 104
students = [1, 2, 3, 4, 5]
students = [i+100 for i in students]
print(students) # [101, 102, 103, 104, 105]

# 학생 이름을 길이로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [len(i) for i in students]
print(students) # [8, 4, 10]

# 학생 이름을 대문자로 변환
students = ["Iron man", "Thor", "I am groot"]
students = [i.upper() for i in students]
print(students) # ['IRON MAN', 'THOR', 'I AM GROOT']

Q5. 당신은 Cocoa 서비스를 이용하는 택시 기사님입니다.

# 50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램을 작성하시오.

# 조건1: 승객별 운행 소요 시간은 5분 ~ 50분 사이의 난수로 정해집니다.
# 조건2: 당신은 소요시간 5분 ~ 15분 사이의 승객만 매칭해야 합니다.

(출력문 예제)

[O] 1번째 손님 (소요시간 : 15분)
[ ] 2번째 손님 (소요시간 : 50분)
[O] 3번째 손님 (소요시간 : 5분)
...
[ ] 50번째 손님 (소요시간 : 16분)

총 탑승 승객: 2분

A1)

from random import *

counts = 0

for customer in range(1,51):
    time = randrange(5, 51)
    if 5 <= time <= 15:
        board = "O"
        counts += 1
    else:
        board = " "
    
    print("[{0}] {1}번째 손님 (소요시간 : {2}분)".format(board, customer, time))
    
print("""
총 탑승 승객: {0}분""".format(counts))

A2)

for random import *
cnt = 0 # 총 탑승 승객 수
for i in range(1, 51): # 1 ~ 50이라는 수 (승객)
    time = randrange(5, 51) # 5분 ~ 50분 소요 시간
    if 5 <= time <= 15: # 5분 ~ 50분 이내의 손님(매칭 성공), 탑승 승객 수 증가 처리
        print("[O] {0}}번째 손님 (소요시간 : {1}분)".format(i, time))
        cnt += 1
    else: # 매칭 실패한 경우
        print("[ ] {0}}번째 손님 (소요시간 : {1}분)".format(i, time))

print("""총 탑승 승객: {0}분""".format(cnt))

함수

1. 함수

def open_account():
    print("새로운 계좌가 생성되었습니다.")

open_account()

2. 전달값과 반환값

def deposit(balance, money):
    print("입금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance + money))
    return balance + money

balance = 0
balance = deposit(balance, 1000)
print(balance)

def withdraw(balance, money):
    if balance >= money: # 잔액이 출금보다 많으면
        print("출금이 완료되었습니다. 잔액은 {0} 원입니다.".format(balance - money))
        return balance - money
    else:
        print("출금이 완료되지 않았습니다. 잔액은 {0} 원입니다.".format(balance))
        return balance

balance = withdraw(balance, 2000)
balance = withdraw(balance, 500)

def withdraw_night(balance, money): # 저녁에 출금
    commission = 100 # 수수료 100원
    return commission, balance - money - commission

balance = 1000
commission, balance = withdraw_night(balance, 500)
print("수수료 {0} 원이며, 잔액은 {1} 원입니다.".format(commission, balance))

3. 기본값

def profile(name, age, main_lang):
    print("이름 : {0}\t나이 : {1}\t주 사용 언어: {2}" \
        .format(name, age, main_lang))

profile("유재석", 20, "파이썬")
profile("김태호", 25, "자바")

# 같은 학교 같은 학년 같은 반 같은 수업
def profile(name, age=17, main_lang="파이썬"):
    print("이름 : {0}\t나이 : {1}\t주 사용 언어: {2}" \
        .format(name, age, main_lang))

profile("유재석")
profile("김태호")

# # 키워드 값
def profile(name, age, main_lang):
    print(name, age, main_lang)

profile(name="유재석", main_lang="파이썬", age= 0)
profile(main_lang="자바", age=25, name="김태호")

4. 가변인자

def profile(name, age, lang1, lang2, lang3, lang4, lang5):
    print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
    print(lang1, lang2, lang3, lang4, lang5)

profile("유재석", 20, "Python", "Java", "C", "C++", "C#")
profile("김태호", 25, "Kotlin", "Swift", "", "", "")

def profile(name, age, *language):
    print("이름 : {0}\t나이 : {1}\t".format(name, age), end=" ")
    for lang in language:
        print(lang, end=" ")
    print()

profile("유재석", 20, "Python", "Java", "C", "C++", "C#", "JavaScript")
profile("김태호", 25, "Kotlin", "Swift")

5. 지역변수와 전역변수

gun = 10 # 전역변수

def checkpoint(soldiers): # 경계근무
    gun = 20 # 지역변수
    gun = gun - soldiers
    print("[함수 내] 남은 총: {0}".format(gun))

print("전체 총 : {0}".format(gun))
checkpoint(2)
print("남은 총 : {0}".format(gun))

def checkpoint(soldiers): # 경계근무
    global gun
    gun = gun - soldiers
    print("[함수 내] 남은 총: {0}".format(gun))

print("전체 총 : {0}".format(gun))
checkpoint(2)
print("남은 총 : {0}".format(gun))

def checkpoint_return(gun, soldiers):
    gun = gun - soldiers
    print("[함수 내] 남은 총: {0}".format(gun))
    return gun

print("전체 총 : {0}".format(gun))
gun = checkpoint_return(gun, 2)
print("남은 총 : {0}".format(gun))

Q6. 표준 체중을 구하는 프로그램을 작성하시오
# 50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램을 작성하시오.

* 표준 체중 : 각 개인의 키에 적당한 체중

(성별에 따른 공식)
남자 : 키(m) x 키(m) x 22
여자 : 키(m) x 키(m) x 21

조건1: 표준 체중은 별도의 함수 내에서 계산
        * 함수명: std_weight
        * 전달값: 키(height), 성별(gender)
조건2: 표준 체중은 소수점 둘째자리까지 표시

(출력 예제)
키 175cm 남자의 표준 체중은 67.38kg 입니다.

A1)

def std_weight(height, gender): # height 단위 cm, gender "여자"/"남자"
    
    height_m = height/100 # m로 조정

    if gender == "여자":
        standard = height_m * height_m * 21
    else:
        standard = height_m * height_m * 22
    
    standard = "%0.2f" % standard
    print("키 {0}cm {1}의 표준 체중은 {2} kg 입니다.".format(height, gender, standard))
    
std_weight(163, "여자")
# 키 163 여자의 표준 체중은 55.79 kg 입니다.

A2)

def std_weight(height, gender): # 키 m 단위 (실수), 성별 "여자" / "남자"
    if gender == "남자":
        return height * height * 22
    else:
        return height * height * 21

height = 175
gender = "남자"
weight = round(std_weight(height/100, gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2} kg 입니다.".format(height, gender, weight))

입출력

1. 표준 입출력

print("Python", "Java", sep=",") # Python,Java
print("Python", "Java", "JavaScript", sep=" vs ") # Python vs Java vs JavaScript

print("Python", "Java", sep=",", end="?")
print("무엇이 더 재밌을까요?")
# Python,Java?무엇이 더 재밌을까요?

import sys
print("Python", "Java", file=sys.stdout) # 표준 출력
print("Python", "Java", file=sys.stderr) # 표준 에러

# 시험 성적
scores = {"수학":0, "영어":50, "코딩":100}
for subject, score in scores.items():
    # print(subject, score)
    print(subject.ljust(8), str(score).rjust(4), sep=":")

# 은행 대기순번표
# 001, 002, 003, ...
for num in range(1, 21):
    print("대기번호 : " + str(num).zfill(3))

# 입력
answer = input("아무 값이나 입력하세요 : ")
print(type(answer)) # <class 'str'>
print("입력하신 값은 " + answer + "입니다.")

2. 다양한 출력 포맷

# 빈 자리는 빈 공간으로 두고, 오른쪽 정렬을 하되, 총 10자리 공간을 확보
print("{0: >10}".format(500)) #        500

# 양수일 땐 +로 표시, 음수일 땐 -로 표시
print("{0: >+10}".format(500)) #       +500
print("{0: >+10}".format(-500)) #      -500 

# 왼쪽 정렬하고, 빈칸을 _로 채움
print("{0:_<+10}".format(500)) # +500______

# 3자리마다 콤마를 찍어주기
print("{0:,}".format(100000000000)) # 100,000,000,000

# 3자리마다 콤마를 찍어주기, +- 부호 붙이기
print("{0:+,}".format(100000000000)) # +100,000,000,000
print("{0:+,}".format(-100000000000)) # -100,000,000,000

# 3자리마다 콤마를 찍어주기, +- 부호 붙이기, 자릿수 확보하기
# 빈 자리는 ^로 채워주기
print("{0:^<+30,}".format(100000000000)) # +100,000,000,000^^^^^^^^^^^^^^

# 소수점 출력
print("{0:f}".format(5/3)) # 1.666667

# 소수점 특정 자리수까지만 표시 (소수점 셋째자리에서 반올림) # 1.67
print("{0:.2f}".format(5/3))

3. 파일입출력

score_file = open("score.txt", "w", encoding="utf8") # w: write
print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
score_file.close()

score_file = open("score.txt", "a", encoding="utf8") # a: append
score_file.write("과학 : 80")
score_file.write("\n코딩 : 100")
score_file.close()

score_file = open("score.txt", "r", encoding="utf8") # r: read
print(score_file.read())
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
print(score_file.readline()) # 줄 별로 읽기, 한 줄 읽고 커서는 다음 줄로 이동
print(score_file.readline()) # 줄 바꿈 안하고 싶으면 print(score_file.readline(), end="")
print(score_file.readline())
print(score_file.readline())
score_file.close()

score_file = open("score.txt", "r", encoding="utf8") # 몇 줄인지 모를 때
while True:
    line = score_file.readline()
    if not line:
        break
    print(line)
score_file.close()

score_file = open("score.txt", "r", encoding="utf8")
lines = score_file.readlines() # list 형태로 저장
for line in lines:
    print(line, end="")
score_file.close()

4. Pickle

import pickle
profile_file = open("profile.pickle", "wb") # b: binary 피클에선 항상 바이너리
profile = {"이름": "박명수", "나이": 30, "취미": ["축구", "골프", "코딩"]}
print(profile)
pickle.dump(profile, profile_file) # profile의 정보를 file에 저장
profile_file.close()

profile_file = open("profile.pickle", "rb")
profile = pickle.load(profile_file) # file에 있는 정보를 profile에 불러오기
print(profile)
profile_file.close()

5. With

import pickle

with open("profile.pickle", "rb") as profile_file:
    print(pickle.load(profile_file))

with open("study.txt", "w", encoding="utf8") as study_file:
    study_file.write("파이썬을 열심히 공부하고 있어요")

with open("study.txt", "r", encoding="utf8") as study_file:
    print(study_file.read())

Q7. 당신의 회사에서는 매주 1회 작성해야 하는 보고서가 있습니다.
# 보고서는 항상 아래와 같은 형태로 출력되어야 합니다.

- X 주차 주간보고 - 
부서 : 
이름 : 
업무 요약 :

1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.

조건 : 파일명은 '1주차.txt', '2주차.txt', ... 와 같이 만듭니다.

A1)

for i in range(1, 51):
    with open(str(i)+"주차.txt", "w", encoding="utf8") as reports:
        reports.write(" - {0} 주차 주간보고 - ".format(str(i)))
        reports.write("\n부서 : ")
        reports.write("\n이름 : ")
        reports.write("\n업무 요약 : ")
728x90