[프로그래밍 언어 & Tool]/Python

두근두근 파이썬(개정판)_ch7 함수 연습문제 1~10번

우당탕탕 개발 일지 2024. 1. 25. 16:56

안녕하세요. 우당탕탕 개발 일지입니다.

파이썬 에디터 IDLE 3.12.1을 사용합니다.

교재 연습문제 1번-10번까지 코드와  풀면서 느낀 점만 올립니다. 

해당 개념만 다룬 블로그 링크 첨부 합니다.

2024.01.25 - [[프로그래밍 언어]/python] - 두근두근 파이썬(개정판)_ch7 함수, def, 인수, 매개변수, 지역변수, 키워드 인수, 디폴트 인수

 

두근두근 파이썬(개정판)_ch7 함수,def, 인수, 매개변수, 지역변수, 키워드 인수, 디폴트 인수

안녕하세요. 우당탕탕 개발 일지입니다. 파이썬 에디터 IDLE 3.12.1을 사용합니다. 책과 수업 내용을 바탕으로 요약한 내용과 교재 뒤 연습문제입니다. ch7 전문제는 푼 링크 첨부 합니다. ※ 오늘

hansol2124.tistory.com

 

 

 

연습문제 ch7-1

이름을 입력받아 생일 축하 노래를 출력하는 함수를 작성하시오.

아무것도 입력 받지 않으면 kim을 이름으로 입력하게 하시오 

def song(person):
        
        print("Happy Birthday to you!\n")
        print("Happy Birthday to you!\n")
        print(f"Happy Birthday to dear {person}")
        print("Happy Birthday to you!")


person=input("생일인 사람의 이름을 입력하시오:")
if (person==""):
    person="kim"
  
 
song(person)

 

if 문을 이용해 아무것도 입력되지 않는 경우에 person에 kim이 들어가게 짰다.

 

 


연습문제 ch7-2

사용자로 부터 2개의 정수를 입력받아 수학문제를 만들어 화면에 출력하는 함수를 작성해 보자. 

def sumproblem(x ,y):
    if n==(x+y):
        print("정답입니다.")
    else:
        print("틀렸습니다.")
    

x=int(input('첫번째 정수'))
y=int(input("두번째 정수"))
n=int(input(f"정수 {x},{y}의 합은?"))
sumproblem(x,y)

 

 


연습문제 ch7-3

pi=3.14로 가정하고 원의 둘레와 원의 넓이를  계산하는 함수를 작성해보자. 

PI=3.14

def circleArea(r):
    area=r*r*PI
    print("반지름이 {}인 원의 면적: {}".format(r,area))

def circleCircumoference(r):
    Circumoference=2*PI*r
    print("반지름이 {}인 원의 둘레: {}".format(r,Circumoference))

r=5
circleArea(r)
circleCircumoference(r)

 

 

 


연습문제 ch7-4

사칙 연산을 수행하는 함수를 각각 작성해보자.

def add(a,b):
    print(f"({a}+{b})={a+b}")

def sub(a,b):
    print(f"({a}-{b})={a-b}")
    
def mul(a,b):
    print(f"({a}*{b})={a*b}")

def div(a,b):
    print(f"({a}/{b})={a/b}")


a=20
b=10
add(a,b)
sub(a,b)
mul(a,b)
div(a,b)

함수이름 뒤에 :붙이는 거 계속 잊음! 주의


연습문제 ch7-5

팩토리얼 계산하는 함수 코드를 작성해 보자.

def factorial(n):
    num=1
    count=1
    while count<=n:
        num*=count
        count+=1
    print(f"{n}!은 {num} 입니다.")


n=int(input("정수를 입력하시오."))
factorial(n)

연습문제 ch7-6

성적을 받아서 학점을 출력하는 함수를 작성해 보자. 

def getGrade(score):
   
    if score>=90:
        print("A학점 입니다.")
    elif score>=80:
        print("B학점 입니다.")
    elif score>=70:
        print("C학점 입니다.")
    elif score>=60:
        print("D학점 입니다.")
    else:
        print("F학점 입니다.")


score=int(input("성적을 입력하시오:"))
getGrade(score)

 

파이썬 하면서 type을 알아서 써주길래 자주 넘어갔는데

int 안 해주니까 score을 if 문 넣을 때 문자열인지 정수인지 알 수 없어서 에러 난다고 뜸


연습문제 ch7-7

F(X)=X^2+1을 계산하는 함수를 작성하고 함수를 이용해 화면에 그래프를 그리는 코드를 작성해 보자. 

import turtle
t=turtle.Turtle()

def coordinate_axis():
    t.up()
    t.goto(0,0)
    t.down()
    t.fd(500)
    t.bk(500)
    t.lt(90)
    t.fd(500)
    t.bk(500)

def fx_func():
    t.pencolor("red")
    x=0
    y=0
    for x in range(1,150):
        x+=1
        y=(x*x+1)*0.01
        t.goto(x,y)


coordinate_axis()
fx_func()

 


연습문제 ch7-8

거북이를 움직이지 않고 선을 긋는 함수를 정의하고 이것을 이용해 거미줄 같은 모양이 그려지게 코드를 작성해보자.

import turtle
t=turtle.Turtle()
s=turtle.Screen()
t.shape("turtle")
s.bgcolor('skyblue')

def draw_snowman(x,y):
    t.fillcolor("white")
    t.begin_fill()#눈사람 머리 
    t.up()
    t.goto(x,y)
    t.down()
    t.circle(50) 
    t.end_fill()

    t.begin_fill()#눈사람 배
    t.up()
    t.goto(x+25,y-25)
    t.down()
    t.left(90)
    t.circle(30,180)#180하면 반원이다.
    t.lt(90)
    t.fd(60)
    t.end_fill()
    
    t.begin_fill();#눈사람 몸통
    t.up()
    t.goto(x-5,y-160)
    t.down()
    t.circle(70)
    t.end_fill()

    t.up()#눈사람 오른쪽 손
    t.goto(x+25,y-25)
    t.lt(45)
    t.down()
    t.fd(60)
    
    t.up()#눈사람 왼쪽 손
    t.goto(x-29,y-25)
    t.lt(90)
    t.down()
    t.fd(60)

    t.up()
    t.home() #시작 위치로 돌아간다.
    t.down()

for i in range(3):
    draw_snowman(200*(i-1),0)

 

 

 


연습문제 ch7-9

눈사람을 그리는 함수를 작성하고 여러 번 호출하여 랜덤한 위치에 눈사람을 그리는 코드를 작성해 보자. 

import turtle
t=turtle.Turtle()
s=turtle.Screen()
t.shape("turtle")
s.bgcolor('skyblue')

def draw_snowman(x,y):
    t.fillcolor("white")
    t.begin_fill()#눈사람 머리 
    t.up()
    t.goto(x,y)
    t.down()
    t.circle(50) 
    t.end_fill()

    t.begin_fill()#눈사람 배
    t.up()
    t.goto(x+25,y-25)
    t.down()
    t.left(90)
    t.circle(30,180)#180하면 반원이다.
    t.lt(90)
    t.fd(60)
    t.end_fill()
    
    t.begin_fill();#눈사람 몸통
    t.up()
    t.goto(x-5,y-160)
    t.down()
    t.circle(70)
    t.end_fill()

    t.up()#눈사람 오른쪽 손
    t.goto(x+25,y-25)
    t.lt(45)
    t.down()
    t.fd(60)
    
    t.up()#눈사람 왼쪽 손
    t.goto(x-29,y-25)
    t.lt(90)
    t.down()
    t.fd(60)

    t.up()
    t.home() #시작 위치로 돌아간다.
    t.down()

for i in range(3):
    draw_snowman(200*(i-1),0)

 

실행시키면서 만들어서 좌표 숫자가 이쁘게 떨어지진 않는다.


연습문제 ch7-10

하나의 가지를 그리는 함수를 작성하고 함수를 여러번 호출하여 눈송이 모양을 그리는 코드를 작성해보자.

 

import turtle
t=turtle.Turtle()
t.pensize(10)
color=['brown', 'light green', 'green', 'yellow','light green','green','blue', 'red']



def draw_branch(c):
    t.color(c)

    for i in range(3):
        t.fd(30)
        t.rt(45)
        t.fd(30)
        t.bk(30)
        t.lt(45)
        t.lt(45)
        t.fd(30)
        t.bk(30)
        t.rt(45)
    
    t.bk(90)


for c in color:
  draw_branch(c)
  t.lt(45)

 

728x90