01. 머리속으로 문제 그려보기
def my_function():
for i in range(1, 20):
if i == 20:
print("You got it")
my_function()
- print() 문구는 i가 20일 때만 출력됨. 다만, range(a,b)는 실제로는 a ~ b-1까지의 숫자들을 발생시킴. 즉, 20이 포함되어 있을 수가 없다. 다음과 같이 수정해야 함.
def my_function():
for i in range(1, 21):
if i == 20:
print("You got it")
my_function()
02. Reproduce the Bug
from random import randint
dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
dice_num = randint(1, 6)
print(dice_imgs[dice_num])
- dice_imgs는 0~5까지 이미지가 들어있음. 즉 dice_imgs[0] ~ dice_imgs[5]
- randint(a,b)는 range(a,b)함수와 달리 a~b까지 숫자 중 하나를 출력함. 즉, dice_num = 6이 될 때 index error가 발생함.
from random import randint
dice_imgs = ["❶", "❷", "❸", "❹", "❺", "❻"]
dice_num = randint(1, 5)
print(dice_imgs[dice_num])
03. play computer
year = int(input("What's your year of birth?"))
if year > 1980 and year < 1994:
print("You are a millenial.")
elif year > 1994:
print("You are a Gen Z.")
- 1994년을 입력하면 아무것도 나오지 않음. if구문에서 1994년은 어디에도 포함되어 있지 않기 때문에.
year = int(input("What's your year of birth?"))
if year > 1980 and year <=1994:
print("You are a millenial.")
elif year > 1994:
print("You are a Gen Z.")
04. Fix the Errors
- indent error 발생.
- age = 12일 경우 TypeError 발생. input으로 입력되는 값들은 모두 string으로 들어오기 때문에.
- f-string 사용하려면 앞에 f 붙여야 함.
05. Print is Your Friend
pages = 0
word_per_page = 0
pages = int(input("Number of pages: "))
word_per_page = int(input("Number of words per page: "))
total_words = pages * word_per_page
print(f"pages = {pages}")
print(f"word_per_page = {word_per_page}")
print(total_words)
- x == y : 등호 두 개를 쓰면 True, False 의 문제로 변함.
- x = y : 등호 한 개를 쓰면 x값이 y값과 같다는 뜻.
06. Use a Debugger
- 위의 코드를 돌리면, 26이라는 값이 산출됨. 예상하는 결과와 다름.
- 들여쓰기를 하지 않았기에, for 구문이 반복되는 동안 new_item값이 b_list에 append되지 않았다.
- 즉, b_list.append를 반복문 안으로 넣어야 함.
def mutate(a_list):
b_list = []
for item in a_list:
new_item = item * 2
b_list.append(new_item)
print(b_list)
mutate([1,2,3,5,8,13])
07. [인터랙티브 코딩 예제] 홀수와 짝수
number = int(input("Which number do you want to check?"))
if number % 2 = 0:
print("This is an even number.")
else:
print("This is an odd number.")
number = int(input("Which number do you want to check? "))
if number % 2 == 0:
print("This is an even number.")
else:
print("This is an odd number.")
- number % 2 = 0 -> number # 2 ==0 으로 바꿔야 number를 2로 나눴을 때 true 일 때는 if 구문이, false 일 때는 else 구문이 실행된다.
- 이중 등호는 확인의 개념, 등호는 할당의 개념!!
- a == b : a와 b가 같은지 확인 후 true, false return
- a = b : a의 값과 b의 값이 같다, a에게 b의 값을 할당한다는 개념.
08. [인터랙티브 코딩 예제] 윤년 문제
year = input("Which year do you want to check?")
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
- input() : 들어오는 입력값은 모두 string으로 들어오므로, int 형식으로 변환 해줘야 함.
year = int(input("Which year do you want to check?"))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year.")
else:
print("Not leap year.")
else:
print("Leap year.")
else:
print("Not leap year.")
09. [인터랙티브 코딩 예제] 피즈-버즈 디버깅
for number in range(1, 101):
if number % 3 == 0 or number % 5 == 0:
print("FizzBuzz")
if number % 3 == 0:
print("Fizz")
if number % 5 == 0:
print("Buzz")
else:
print([number])
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
elif number % 3 == 0:
print("Fizz")
elif number % 5 == 0:
print("Buzz")
else:
print(number)
- 3으로 나눠지는 수는 fizz, 5로 나눠지는 수는 buzz, 3과 5로 둘 다 나눠지는 숫자는 fizzbuzz가 나와야 한다.
- print([number]) -> print(number) 숫자가 출력될 당시 [] 안에 넣어지지 않은 상태에서 출력됨.
- 3과 5로 둘 다 나눠져야 하므로, or -> and으로 바꿔줘야 함.
- 또한 숫자는 모든 조건이 거짓이어야 출력되어야 하므로 if, elif, else 구문으로 바꿔줘야 함.