CHAPTER 5. 조건
x == y
x != y
x > y
x < y
x >= y
x <= y
x and y
x or y
not x
if / elif / if - if else
P = 'A' if j >= 90 else 'B'
P = 'A' if j>=90 else('B' if j >=80 else 'C')
1. 사용자로부터 성적을 입력받아서 합격 여부를 판단하는 프로그램
score = int(input("성적을 입력하세요"))
if score >= 60:
print("합격")
else:
print("불합격")
2. 사용자로부터 정수를 입력받아서 짝수인지 홀수인지를 검사하는 프로그램
num = int(input("정수를 입력하시오 : "))
if num % 2 ==0:
print("짝수")
else :
print("홀수")
3.정수의 부호에 따라 거북이를 움직이자
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.penup()
t.goto(100,100)
t.write("거북이가 여기로 오면 양수입니다.")
t.goto(100,0)
t.write("거북이가 여기로 오면 0입니다.")
t.goto(100,-100)
t.write("거북이가 여기로 오면 음수입니다.")
num = int(input("숫자를 입력하세요"))
if num > 0:
t.goto(100,100)
t.pendown()
t.circle(10)
if num == 0:
t.goto(100,0)
t.pendown()
t.circle(10)
if num < 0:
t.goto(100,-100)
t.pendown()
t.circle(10)
4. 영화 나이 제한 검사
age = int(input("나이를 입력하시오 : "))
if age > 15 :
print("영화 가능")
print("영화의 가격은 10,000원 입니다")
else :
print("불가능")
print("다른 영화를 보시겠어요?")
5. 거북이 제어하기
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.width(3)
t.shapesize(3,3)
while True :
move = input("명령을 입력하시오")
if move == 'r' :
t.right(90)
t.forward(100)
if move == 'l' :
t.left(90)
t.forward(100)
6. 윤년판단
year = int(input("연도를 입력하시오"))
if (year % 4 ==0) and (year % 100 != 0) or (year % 400 ==0) :
print("윤년입니다")
else :
print("윤년이 아닙니다")
7. 동전 던지기 게임
import random
import turtle
screen = turtle.Screen()
t = turtle.Turtle()
image1 = "C:\\폴더\\1.gif"
image2 = "C:\\폴더\\2.gif"
screen.addshape(image1)
screen.addshape(image2)
while True :
print("동전 던지기 게임을 시작")
num = random.randrange(2)
if num == 0 :
t.shape(image1)
t.stamp()
print("1")
else :
t.shape(image2)
t.stamp()
print("2")
print("게임 종료")
8. 종달새가 노래할까?
import random
time = random.randint(1,24)
sunny = random.choice([True, False])
print("좋은 아침입니다. 지금 시각은 " + str(time) + "시 입니다")
if sunny == True :
print("현재날씨가 화창합니다")
else :
print("현재날씨가 화창하지 않습니다")
if (time > 5) and (time < 10) and (sunny == True):
print("종달새가 노래한다")
else :
print("종달새가 노래하지 않습니다.")
9. 도형 그리기
import turtle
t = turtle.Turtle()
t.shape("turtle")
s = turtle.textinput("", "도형을 입력하시오(사각형, 삼각형, 원형) :")
if s == "사각형" :
s = turtle.textinput("","가로 :")
w = int(s)
s = turtle.textinput("","세로 :")
h = int(s)
t.forward(w)
t.left(90)
t.forward(h)
t.left(90)
t.forward(w)
t.left(90)
t.forward(h)
if s == "원형" :
s = turtle.textinput("","지름 :")
r = int(s)
t.circle(r)
if s == "삼각형" :
s = turtle.textinput("","밑변 :")
w = int(s)
s = turtle.textinput("","높이 :")
h = int(s)
t.forward(w)
t.left(90)
t.forward(h)
t.goto(0,0)
10. 축약형
score = int(input("성적을 입력하시오 :"))
if score >= 90 :
print("A")
elif score >= 80 :
print("B")
elif score >= 70 :
print("C")
elif score >= 60 :
print("D")
else :
print("F")
print('A' if score >= 90 else('B' if score >=80 else ('C' if score >= 70 else('D' if score >=60 else 'F'))))
CHAPTER 6. 반복
1. n각형 그리기
import turtle
t = turtle.Turtle()
t.shape("turtle")
s = turtle.textinput("", "몇각형을 원하시나요? :")
n = int(s)
for i in range(n):
t.forward(100)
t.left(360/n)
2. 거북이 랜덤 움직임
import random
import turtle
t = turtle.Turtle()
t.shape("turtle")
for i in range(1, 11, 1) :
number = random.randint(1,100)
deg = random.randint(-180,180)
length = number
t.forward(length)
t.left(deg)
3. 팩토리얼 계산하기
n = int(input("정수를 입력하시오 : "))
fact = 1
for i in range(1, n+1):
fact = fact * i
print(n, "!은 ", fact, "이다")
4. 구구단
n = int(input("원하는 단은 : "))
i = 1
while i<= 9:
print("%s*%s=%s" %(n, i, n*i))
i = i + 1
5. 스파이럴 그리기
import turtle
t = turtle.Turtle()
t. shape("turtle")
colors = ["red", "purple", "blue", "green", "yellow", "orange"]
t.speed(0)
t.width(3)
turtle.bgcolor("black")
len = 10
while len < 1000:
t.forward(len)
t.pencolor(colors[len%6])
t.right(89)
len += 5
p181 사용자가 입력하는 숫자의 합 계산하기
total = 0
answer = "yes"
while answer == "yes" :
num = int(input("숫자입력 : "))
total += num
answer = input("계속?(yes or no) : ")
else :
print("합계 : " , total)
p183 숫자 맞추기 게임
import random
num_ran = random.randint(1,100)
guess = 0
while True:
num_in = int(input("숫자를 입력하세요 :"))
guess += 1
if num_ran < num_in:
print("높음!")
elif num_ran > num_in:
print("낮음!")
else:
print("축하합니다.")
break
print(guess, "번 숫자를 입력했습니다.")
p185 초등생을 위한 산수 문제 발생기
import random
while True :
num1 = random.randint(1,100)
num2 = random.randint(1,100)
print(num1,"+",num2)
answer = int(input("정답은?"))
if( answer == num1+num2) :
print("ok")
else :
print("not good")
p186 모든 샌드위치 종류 출력하기
CHAPTER 7. 함수
def get_sum(start, end) :
Sum = 0
for i in range(start, end+1) :
Sum += i
return Sum,i
hap, gae=get_sum(1, 10)
print(hap,gae)
p206 사각형을 그리는 함수 작성
import turtle
t = turtle.Turtle()
t.shape("turtle")
def turtle_rec(length) :
for i in range(4) :
t.forward(length)
t.left(90)
turtle_rec(100)
t.up()
t.forward(200)
t.down()
turtle_rec(100)
t.up()
t.forward(200)
t.down()
turtle_rec(100)
p214 클릭하는 곳에 사각형 그리기
import turtle
t = turtle.Turtle()
t.shape("turtle")
def turtle_rec(length) :
for i in range(4) :
t.forward(length)
t.left(90)
def drawit(x, y) :
t.up()
t.goto(x, y)
t.down()
t.begin_fill()
t.color("green")
turtle_rec(100)
t.end_fill()
s = turtle.Screen()
s.onscreenclick(drawit)
p216 마우스로 그림 그리기
import turtle
def drawit(x, y) :
t.goto(x,y)
t = turtle.Turtle()
t.shape("turtle")
t.pensize(10)
s = turtle.Screen()
s.onscreenclick(drawit)
s.onkey(t.up, "Up")
s.onkey(t.down, "Down")
s.listen()
p221 터틀 메이즈 러너
import turtle
import random
def draw_maze(x, y) :
for i in range(2):
t.up()
if i== 1 :
t. goto(x+100, y+100)
else :
t. goto(x, y)
t.down()
t.forward(300)
t.right(90)
t.forward(300)
t.left(90)
t.forward(300)
def turn_left() :
t.left(10)
t.forward(10)
def turn_right() :
t.right(10)
t.forward(10)
t = turtle.Turtle()
screen = turtle.Screen()
t.shape("turtle")
t.speed(0)
draw_maze(-300, 200)
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")
t.up();
t.goto(-300, 250)
t.speed(1)
t.down();
screen.listen()
screen.mainloop()
CHAPTER 9. 리스트와 딕셔너리
import turtle
import random
t1 = turtle.Turtle()
t1.shape("turtle")
t1.pensize(4)
t1.penup()
t1.goto(-300,0)
t2 = turtle.Turtle()
t2.shape("turtle")
t2.pensize(4)
t2.penup()
t2.goto(-300,-100)
t3 = turtle.Turtle()
t3.color("red")
t3.pensize(4)
t3.penup()
t3.goto(0,100)
t3.pendown()
t3.right(90)
t3.forward(300)
t1.pendown()
t2.pendown()
score1 = 0
score2 = 0
for i in range(20) :
d1 = random.randint(1,50)
d2 = random.randint(1,50)
t1.forward(d1)
t2.forward(d2)
score1 += d1
score2 += d2
if score1 > 300 :
print("1번 거북이 승")
break
elif score2 > 300 :
print("2번 거북이 승")
break
----------------------------
import turtle
def draw_shape(radius, color1) :
t.left(270)
t.width(3)
t.color("black",color1)
t.begin_fill()
t.circle(radius/2.0, -180)
t.circle(radius, 180)
t.left(180)
t.circle(-radius/2.0, -180)
t.end_fill()
t = turtle.Turtle()
t.reset()
draw_shape(200, "red")
t.setheading(180)
draw_shape(200, "blue")
----------------------------
import turtle
import math
player = turtle.Turtle()
player.shape("turtle")
screen = player.getscreen()
def turnleft() :
player.left(5)
def turnright() :
player.right(5)
def fire() :
x = 0
y = 0
velocity = 50
angle = player.heading()
vx = velocity * math.cos(angle * 3.14 / 180.0)
vy = velocity * math.sin(angle * 3.14 / 180.0)
while player.ycor() >= 0 :
vx = vx
vy = vy -10
x = x +vx
y = y+ vy
player.goto(x, y)
screen.onkeypress(turnleft, "Left")
screen.onkeypress(turnright, "Right")
screen.onkeypress(fire, "space")
screen.listen()
----------------------------
import random
quotes = []
quotes.append('a')
quotes.append('A')
quotes.append('d')
quotes.append(1)
quotes.append(5)
print("#############################")
print("########오늘의 속담###########")
print("##############################")
print(quotes.sort())
print(random.choice(quotes))
----------------------------
import turtle
import random
import math
player = turtle.Turtle()
player.color("blue")
player.shape("turtle")
player.penup()
player.speed(0)
screen = player.getscreen()
asteroids = []
for i in range(10) :
a1 = turtle.Turtle()
a1.color("red")
a1.shape("circle")
a1.penup()
a1.speed(0)
a1.goto(random.randint(-300,300), random.randint(-300,300))
asteroids.append(a1)
def turnleft() :
player.left(30)
def turnright() :
player.right(30)
screen.onkeypress(turnleft, "Left")
screen.onkeypress(turnright, "Right")
screen.listen()
def play() :
player.forward(2)
for a in asteroids:
a.right(random.randint(-180,180))
a.forward(2)
screen.ontimer(play, 10)
screen.ontimer(play, 10)
----------------------------
a = []
average = 0
for i in range(5) :
numbers = int(input("숫자를 입력하시오 :"))
a.append(numbers)
average += a[i]
print("평균은 " + str(average/len(a)) + "입니다")
----------------------------
import random
counters = [0, 0, 0, 0, 0, 0]
count = 0
for i in range(100) :
value = random.randint(0,5)
counters[value] = counters[value] + 1
count += 1
print("주사위를 "+str(count) + "번 던졌습니다")
for i in range(6) :
print(str(i+1)+"은 " +str(counters[i]) +"번")
------------------------------------------------------
counters = [0 for i in range(6)]
for i in range(100) :
counters[random.randint(0,5)] += 1
print("주사위를 100번 던졌습니다")
for i in range(1,6) :
print(str(i)+"은 " +str(counters[i]) +"번")
print("6은 " +str(counters[0]) +"번")
----------------------------
CHAPTER 10. tkinter로 GUI 만들기
p290 grid 연습
from tkinter import *
window = Tk()
l1 = Label(window, text = "화씨")
l2 = Label(window, text = "섭씨")
l1.grid(row = 0, column=0)
l2.grid(row = 1, column=0)
e1 = Entry(window)
e2 = Entry(window)
e1.grid(row = 0, column=1)
e2.grid(row = 1, column=1)
b1 = Button(window, text = "화씨 -> 섭씨")
b2 = Button(window, text = "화씨 -> 섭씨")
b1.grid(row = 2, column=0)
b2.grid(row = 2, column=1)
window.mainloop()
p292 이벤트 처리
from tkinter import *
def process() :
temperature = float(e1.get())
mytemp = (temperature-32)*5/9
e2.insert(0, str(mytemp))
def clear() :
e2.insert(0, 0)
window = Tk()
l1 = Label(window, text = "화씨")
l2 = Label(window, text = "섭씨")
l1.grid(row = 0, column=0)
l2.grid(row = 1, column=0)
e1 = Entry(window)
e2 = Entry(window)
e1.grid(row = 0, column=1)
e2.grid(row = 1, column=1)
b1 = Button(window, text = "화씨 -> 섭씨", command = process)
b2 = Button(window, text = "화씨 -> 섭씨")
b1.grid(row = 2, column=0)
b2.grid(row = 2, column=1)
b3 = Button(window, text = "clear", command = clear)
b3.grid(row = 3, column=3)
window.mainloop()
->
l1 = Label(window, text = "화씨")
l2 = Label(window, text = "섭씨")
l1.place(x=0, y= 111)
l2.grid(row = 1, column=0)
pack, grid, place 로 레이블의 위치 표현 가능
p292 이벤트 처리
from tkinter import *
def change_img() :
path = inputBox.get()
img = PhotoImage(file = path)
imageLabel.configure(image = img)
imageLabel.image = img
window = Tk()
photo = PhotoImage(file = "ho.gif")
imageLabel = Label(window, image = photo)
imageLabel.pack()
inputBox = Entry(window)
inputBox.pack()
button = Button(window, text='Submit', command = change_img)
button.pack()
window.mainloop()