[Zerobase][Python Basic] 문제풀이

솔비·2023년 11월 26일

💻 Python. w/zerobase

목록 보기
3/33
post-thumbnail

변수와 입출력

🌟len()

문자열 길이반환 함수

message = 'hello python'
print('메세지 문자열입력 : {}'.format(len(message)))
#메세지 문자열입력 : 12

🌟.find(문자열)

특정문자열의 위치반환 매서드

message = 'hello python'
find = message.find('python')
print('python 위치반환 : {}'.format(find))
#python 위치반환 : 6

🌟.isdigit()

숫자 판별 매서드
숫자면 True / 문자면 False

#체중과 신장을 입력하면 BMI 지수가 출력되는 프로그램
weight = input('체중입력(g) : ')
height = input('신장입력(cm) : ')

if weight.isdigit() :
    weight = int(weight) / 10

if height.isdigit() :
    height = int(height) / 100

print('체중 : {}'.format(weight))
print('신장 : {}'.format(height))

bmi = weight / (height ** 2)
print('BMI : %.2f' %bmi)

datetime 모듈

local date의 날짜와 시간을 다루는 모듈

#나이가 100살 되는 해의 연도를 구하는 프로그램
import datetime

today_year = datetime.datetime.today().year
age = input('나이입력 : ')

if age.isdigit() :
    after_age = 100 - int(age)
    year_100 = today_year + after_age

    print('{}년 후 100살({})'.format(after_age,year_100))

else :
    print('숫자로 입력해주세요.')

🌟 datatime.datetime.today()

  • datatime.datetime.today().year : 년도
  • datatime.datetime.today().month : 월
  • datatime.datetime.today().day : 일
  • datatime.datetime.today().hour : 시
  • datatime.datetime.today().minute : 분
  • datatime.datetime.today().second : 초
today = datetime.datetime.today()
print(today)
# 2023-11-26 15:58:47.023460

print(today.year)
print(today.month)
print(today.day)
print(today.hour)
print(today.minute)
print(today.second)

#2023
#11
#26
#15
#58
#47

format의 %f 복습

#원의 반지름을 입력하면 원의 넓이와 둘레길이를 출력하되,
#정수, 소수점한자리, 소수점 두자리를 각각 출력하라
r = int(input('반지름(cm)입력 : '))

area = r * r * 3.14
round = 2 * 3.14 * r

print('원의넓이 : %d' %area)
print('원의둘레 : %d' %round)
print('원의넓이 : %.1f' %area)
print('원의둘레 : %.1f' %round)
print('원의넓이 : %.2f' %area)
print('원의둘레 : %.2f' %round)

연산자

📖 연습문제 1번

상품가격과 지불금액을 입력하면 거스름돈을 계산하는 프로그램을 만들자
단, 거스름 돈은 지폐와 동전의 개수를 최소로 하고, 1원단위는 절사한다.

money_50000 = 0
money_10000 = 0
money_5000 = 0
money_1000 = 0
money_500 = 0
money_100 = 0
money_10 = 0

price = int(input('상품가격 입력 : '))
give = int(input('지불금액 : '))

pay_back = (give - price) // 10 * 10
print('거스름돈 : {}(원단위 절사)'.format(pay_back))
print('-'*60)

if pay_back >= 50000 :
    money_50000 = pay_back // 50000
    pay_back %= 50000

if pay_back >= 10000 :
    money_10000 = pay_back // 10000
    pay_back %= 10000

if pay_back >= 5000:
    money_5000 = pay_back // 5000
    pay_back %= 5000

if pay_back >= 1000:
    money_1000 = pay_back // 1000
    pay_back %= 1000

if pay_back >= 500:
    money_500 = pay_back // 500
    pay_back %= 500

if pay_back >= 100:
    money_100 = pay_back // 100
    pay_back %= 100

if pay_back >= 10:
    money_10 = pay_back // 10
    pay_back %= 10

print('50,000 {}장'.format(money_50000))
print('10,000 {}장'.format(money_10000))
print('5,000 {}장'.format(money_5000))
print('1,000 {}장'.format(money_1000))
print('500 {}개'.format(money_500))
print('100 {}개'.format(money_100))
print('10 {}개'.format(money_10))

📋 해결방법 기록

나같은경우, 지폐와 동전의 개수만 변수에 담았는데 문제풀이는 지폐금액까지 변수에 담아서 코딩했다.
최대한 변수에 담는게 나중 수정을 위해 좋다고 배웠는데, 수기입력이 아닌 변수에 담는 습관을 들여야겠다.

📖 연습문제 2번

국어 영어 수학점수를 입력 후 총점, 평균, 최고점수과목, 최저점수 과목
그리고 최고점수와 최저점수의 차이를 각각 출력하라

kor = int(input('국어 점수 입력 : '))
eng = int(input('영어 점수 입력 : '))
math = int(input('수학 점수 입력 : '))

sum_score = kor + eng + math
avg_score = sum_score / 3

scores = {'국어' : kor, '영어' : eng, '수학' : math}

max_score = 0
max_subject = ''
for subject, score in scores.items() :
    if max_score < score :
        max_score = score
        max_subject = subject

min_score = max_score
min_subject = ''
for subject, score in scores.items() :
    if min_score > score :
        min_score = score
        min_subject = subject

sub_max_min = max_score - min_score

print('총점 : {}'.format(sum_score))
print('평균 : %.2f' % avg_score)
print('-'*60)
print('최고 점수 과목(점수) : {}({})'.format(max_subject,max_score))
print('최저 점수 과목(점수) : {}({})'.format(min_subject,min_score))
print('최고, 최저 점수 차이 : {}'.format(sub_max_min))
print('-'*60)

📋 해결방법 기록

문제풀이의 경우
kor 점수를 max_score로 일단 초기화하고
if를 이용해
eng, math 점수를 비교하여 max_score를 재초기화 시켰다.
나같은 경우 딕셔너리가 생각 나 scores에 각 과목과 점수를 key와 value로 담고 for문에 넣어 비교했다.
코드의 길이는 거의 비슷한것같다.😅

📖 연습문제 3번

197개의 빵과 152개의 우유를 17명의 학생한테 동일하게 나눠준다고할때
한 학생이 갖게되는 빵과 우유의 개수와 남는 빵과 우유개수는?

bread = 197
milk = 152
student = 17

bread = divmod(bread,student)
milk = divmod(milk,student)

print('학생 한명이 갖게되는 빵: {} / 우유 : {}'.format(bread[0],milk[0]))
print('남는 빵: {} / 우유 : {}'.format(bread[1],milk[1]))

📋 해결방법 기록

// 목과 %나머지 연산자를 이용해 각각 구해도 되지만, divmod 함수를 써보지 않아서
divmod 함수와 인덱스를 활용하여 풀이해보았다.

📖 연습문제 4번

고도가 60m 올라갈 떄 마다 기온이 0.8도 내려간다고 할때
고도를 입력하면 기온이 출력되는 프로그램을 만들어보자 (지면온도 29)


base_temp = 29
step = 60
step_temp = 0.8

height = int(input('고도입력 : '))

m_temp = step_temp / step
result = base_temp - height * m_temp

print('고도 {}m의 지면온도 : {}'.format(height,result))

📖 연습문제 5번

다음내용을 참고해서 백신 접종 대상자를 구분하기 위한 프로그램을 만들어보자

19세 이하 65세 이상이면, 출생연도 끝자리에 따른 접종
그렇지 않으면 하반기 일정 확인

age = int(input('나이 입력 : '))

if age >= 65 or age <= 19 :
    birth = int(input('출생연도 끝자리 입력 : '))
    if birth == 0 or birth == 1 :
        print('월요일 접종 가능')
    elif birth == 2 or birth == 3 :
        print('화요일 접종 가능')
    elif birth == 4 or birth == 5 :
        print('수요일 접종 가능')
    elif birth == 6 or birth == 7 :
        print('목요일 접종 가능')
    elif birth == 8 or birth == 9 :
        print('금요일 접종 가능')
else :
    print('하반기 일정을 확인하세요.')

📋 해결방법 기록

and 와 or을 구별하는 문제
실제로 모든 or을 and로 써서 계속 else문이 출력되었다. 😅
항상 문제에 둘 중 하나만 해당하면 인지 (or)
둘 다 해당인지 (and)를 잘 보아야 할 것같다.


제로베이스 데이터취업스쿨
Daily Study Note
profile
Study Log

0개의 댓글