python 기초 문제 풀이

David Kim·2023년 3월 9일
0

python기초

목록 보기
6/6
post-thumbnail

기초 문제 풀이

  • isdigit()
    isdigit()는 문자열이 숫자로 이루어져 있는지 여부를 판별하는 메소드입니다.
    숫자로 이루어져 있으면 True를 반환하고, 그렇지 않으면 False를 반환합니다.
    이 메소드는 문자열이 실수형으로 이루어져 있는지 여부를 판별하지는 않습니다.

datetime 모듈

파이썬 내장 모듈 중 하나로, 날짜와 시간과 관련된 데이터를 다룰 때 유용합니다.
datetime 모듈은 date, time, datetime, timedelta, tzinfo 등의 클래스를 제공하며, 이들 클래스를 사용하여 날짜와 시간을 처리할 수 있습니다.

  • datetime 모듈의 주요 기능은 다음과 같습니다.
  1. date 클래스: 날짜를 다루는 기능을 제공합니다.
  2. time 클래스: 시간을 다루는 기능을 제공합니다.
  3. datetime 클래스: 날짜와 시간을 함께 다루는 기능을 제공합니다.
  4. timedelta 클래스: 두 날짜와 시간의 차이를 계산하는 기능을 제공합니다.
  5. tzinfo 클래스: 시간대(timezone)를 처리하는 기능을 제공합니다.

연산자 %가 아직 익숙하지 않아서 개념이 헷갈릴때가 많다.

e.g., changeMoney %= money50000

changeMoney %= money50000는 현재 남은 거스름돈(changeMoney)을 50,000원짜리 지폐로 나눈 나머지를 changeMoney에 할당하는 코드입니다.

%=는 현재 변수 값에 대한 나머지 연산 후, 결과를 다시 해당 변수에 할당하는 축약 연산자입니다.

예를 들어, changeMoney가 120,000원이고, money50000이 50,000원이라면, changeMoney %= money50000는 changeMoney를 50,000으로 나눈 나머지(20,000원)를 changeMoney에 할당하게 됩니다.



changeMoney = 120000
money50000 = 50000

changeMoney %= money50000  # 20,000을 계산하고 changeMoney에 할당
print(changeMoney)  # 출력결과: 20000

상품 가격과 지불 가격, 거스름돈 및 지폐 단위 계산

money50000 = 50000; money10000 = 10000; money5000 = 5000; money1000 = 1000
money500 = 500; money100 = 100; money10 = 10

money50000Cnt = 0; money10000Cnt = 0; money5000Cnt = 0; money1000Cnt = 0
money500Cnt = 0; money100Cnt = 0; money10Cnt = 0

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

if payPrice > productPrice:
    changeMoney = payPrice - productPrice
    changeMoney = (changeMoney // 10) * 10
    print('거스름돈: {},(원단위 절사)'.format(changeMoney))

if changeMoney > money50000:
    money50000Cnt = changeMoney // money50000
    changeMoney %= money50000

if changeMoney > money10000:
    money10000Cnt = changeMoney // money10000
    changeMoney %= money10000

if changeMoney > money5000:
    money5000Cnt = changeMoney // money5000
    changeMoney %= money5000

if changeMoney > money1000:
    money1000Cnt = changeMoney // money1000
    changeMoney %= money1000

if changeMoney > money500:
    money500Cnt = changeMoney // money500
    changeMoney %= money500

if changeMoney > money100:
    money100Cnt = changeMoney // money100
    changeMoney %= money100

if changeMoney > money10:
    money10Cnt = changeMoney // money10
    changeMoney %= money10

print('-' * 25)
print('50,000원 {}장'.format(money50000Cnt))
print('10,000원 {}장'.format(money10000Cnt))
print('5,000원 {}장'.format(money5000Cnt))
print('1,000원 {}장'.format(money1000Cnt))
print('500원 {}장'.format(money500Cnt))
print('100원 {}장'.format(money100Cnt))
print('10원 {}장'.format(money10Cnt))
print('-' * 25)

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

korScore = int(input('국어 점수 입력:'))
engScore = int(input('영어 점수 입력:'))
mathScore = int(input('수학 점수 입력:'))

totalScore = korScore + engScore + mathScore
avgScore = totalScore / 3

maxScore = korScore
maxSubject = '국어'

if engScore > maxScore:
    maxScore = engScore
    maxSubject = '영어'

if mathScore > maxScore:
    maxScore = mathScore
    maxSubject = '수학'

minScore = korScore
minSubject = '국어'

if engScore < minScore:
    minScore = engScore
    minSubject = '영어'

if mathScore < minScore:
    minScore = mathScore
    minSubject = '수학'

difScore = maxScore - minScore

print('총점: {}'.format(totalScore))
print('평균 %.2f' % avgScore)
print('-' * 30)
print('최고 과목(점수): {}({})'.format(maxSubject, maxScore))
print('최저 과목(점수): {}({})'.format(minSubject, minScore))
print('최고, 최저 점수 차이: {}'.format(difScore))
print('-' * 30)

금액, 이율, 거치기간 입력하여 복리 계산

money = int(input('금액 입력: '))
interest = float(input('이율 입력: '))
term = int(input('기간 입력: '))

targetMoney = money

for i in range(term):
    targetMoney += (targetMoney * interest * 0.01)

targetMoneyFormated = format(int(targetMoney),',')

print('-' * 30)
print('이율 : {}% '.format(interest))
print('원금 : {}원 '.format(format(money),()))
print('{}년 후 금액 : {}원 '.format(term, targetMoneyFormated))
print('-' * 30)

위 코드는 사용자로부터 금액, 이율, 기간을 입력받아, 이자를 반영한 금액을 계산하고, 이를 특정 포맷으로 출력하는 파이썬 코드입니다.

targetMoneyFormated 변수에는 targetMoney 변수에 누적된 금액을 format() 함수를 이용해 천 단위마다 콤마(,)를 찍은 문자열로 변환하여 할당합니다. 그리고 마지막으로 print() 함수를 이용해 이자율, 원금, 기간, 그리고 이자를 반영한 금액을 출력합니다.

따라서 위 코드를 실행하면, 사용자로부터 금액, 이율, 기간을 입력받아 이자를 반영한 금액이 특정 포맷으로 출력됩니다.

조건문 연습 문제

제한 속도 if

speed = int(input('속도 입력 : '))

if speed <= 50:
    print('안전속도 준수')
    print(f'현재 속도: {speed}(km)')

if speed > 50:
    print('안전속도 위반!! 과태료 50,000원 부과 대상')
    print(f'현재 속도: {speed}(km)')

제한 속도 else

speed = int(input('속도 입력 : '))
limitSpeed = 50

if speed <= 50:
    print('안전속도 준수')
    print(f'현재 속도: {speed}(km)')
    print('최대 속도: {}(km)'.format(limitSpeed))

else:
    print('안전속도 위반!! 과태료 50,000원 부과 대상')
    print(f'현재 속도: {speed}(km)')
    print('최대 속도: {}(km)'.format(limitSpeed))

메세지 발송

text = input('메세지를 입력하세요: ')
textLength = len(text)
msgPrice = 0


if textLength <= 50:
    msgPrice = 50
    print('SMS발송!!')
    print('메세지 길이: {}문자'.format(textLength))
    print('메세지 발송 요금: {}원'.format(msgPrice))

else:
    msgPrice = 50
    print('MMS 발송!!')
    print('메세지 길이: {} 문자'.format(textLength))
    print('메세지 발송 요금: {}원'.format(msgPrice))

편차 구하기

korScore = int(input('국어 점수 입력: '))
engScore = int(input('영어 점수 입력: '))
mathScore = int(input('수학 점수 입력: '))
scienceScore = int(input('과학 점수 입력: '))
historyScore = int(input('국사 점수 입력: '))

total = korScore + engScore + mathScore + scienceScore + historyScore
avg = total / 5

korAvgScore = 85; engAvgScore = 82; mathAvgScore = 89; scienceAvgScore = 75; historyAvgScore = 94

totalAvgScore = korAvgScore + engAvgScore + mathAvgScore + scienceAvgScore + historyAvgScore
avgScore = totalAvgScore / 5

korGap = korScore - korAvgScore
engGap = engScore - engAvgScore
mathGap = mathScore - mathAvgScore
scienceGap = scienceScore - scienceAvgScore
historyGap = historyScore - historyAvgScore
avgGap = int(avg - avgScore)

print('총점: {}({})'.format(total, (total - totalAvgScore)), end=''), \
    print('평균: {}({})'.format(avg, (avg - avgScore)))
print('-'* 70)
print('내 점수(편차)')
print('국어: {}({}), 영어: {}({}), 수학: {}({}), 과학: {}({}), 국사: {}({})'
      .format(korScore, korGap, engScore, engGap, mathScore, mathGap, scienceScore, scienceGap, historyScore, historyGap))
print('-'* 70)
str = '+' if korGap > 0 else '-'
print('국어 편차: {}({})'.format(str * abs(korGap), korGap))
str = '+' if engGap > 0 else '-'
print('영어 편차: {}({})'.format(str * abs(engGap), engGap))
str = '+' if mathGap > 0 else '-'
print('수학 편차: {}({})'.format(str * abs(mathGap), mathGap))
str = '+' if scienceGap > 0 else '-'
print('과학 편차: {}({})'.format(str * abs(scienceGap), scienceGap))
str = '+' if historyGap > 0 else '-'
print('국사 편차: {}({})'.format(str * abs(historyGap), historyGap))
str = '+' if (avg - avgScore) > 0 else '-'
print('평균 편차: {}({})'.format(str * abs(avgGap), avgGap))
print('-' * 70)

홀짝 게임은 컴퓨터와 사용자 간의 게임으로, 사용자가 숫자를 입력하고, 컴퓨터가 무작위로 홀수 또는 짝수를 선택하는 게임입니다. 만약 사용자가 선택한 숫자와 컴퓨터가 선택한 홀수 또는 짝수가 일치하면 사용자가 이기게 됩니다.

파이썬으로 홀짝 게임을 만들려면, 먼저 사용자로부터 숫자를 입력받아야 합니다. 이를 위해 input 함수를 사용할 수 있습니다. 그런 다음, 사용자가 입력한 숫자가 홀수인지 짝수인지를 확인해야 합니다. 이를 위해 % 연산자를 사용할 수 있습니다. % 연산자는 나머지를 반환하는 연산자이기 때문에, 만약 숫자를 2로 나눈 나머지가 0이라면 그 숫자는 짝수이고, 나머지가 1이라면 그 숫자는 홀수입니다.

그 다음, 컴퓨터가 홀수 또는 짝수를 선택하도록 코드를 작성해야 합니다. 이를 위해 random 모듈을 사용할 수 있습니다. random 모듈은 무작위 수를 생성하는 함수인 randint 함수를 제공합니다. 이 함수를 사용하여 0 또는 1 중에 하나를 무작위로 선택하면, 그 값이 0이면 컴퓨터가 짝수를 선택한 것이고, 그 값이 1이면 컴퓨터가 홀수를 선택한 것입니다.

마지막으로, 사용자가 선택한 숫자와 컴퓨터가 선택한 홀수 또는 짝수를 비교하여 게임의 승패를 결정하면 됩니다.

다음은 파이썬으로 홀짝 게임을 만들기 위한 예시 코드입니다:

import random

num = int(input("숫자를 입력하세요: "))
if num % 2 == 0:
    user_choice = "짝수"
else:
    user_choice = "홀수"

computer_choice = random.choice(["짝수", "홀수"])
print(f"사용자 선택: {user_choice}")
print(f"컴퓨터 선택: {computer_choice}")

if user_choice == computer_choice:
    print("승리!")
else:
    print("패배!")

이 코드는 먼저 사용자로부터 숫자를 입력받고, 입력받은 숫자가 홀수인지 짝수인지를 확인합니다. 그런 다음, random.choice 함수를 사용하여 컴퓨터가 짝수 또는 홀수 중에 하나를 무작위로 선택하도록 합니다.
마지막으로, 사용자가 선택한 숫자와 컴퓨터가 선택한 홀수 또는 짝수를 비교하여 게임의 승패를 출력합니다.

0개의 댓글