강의

멘토링

로드맵

Inflearn Community Q&A

1019jinjune's profile image
1019jinjune

asked

Dr. Nam's Python Basics, 100% Practical Use

Making a Number Baseball Game (Python Basics, Random Functions, Loops, Conditional Statements)

24번째 줄 에서의 오류 ..?

Written on

·

200

1

import random
numbers =[]
number = str(random.randint(0,9))
#문자열로 다룬다, 문자열로 다루는 이유?
#코딩하다보면 안다.

for i in range(3):
#3번 반복
while number in numbers:
number = str(random.randint(0,9))
numbers.append(number)

count_strike = 0
count_ball = 0

while count_strike < 3:
count_strike = 0
count_ball = 0

num = str(input("숫자 3자리를 입력하세요 : "))
if len(num) == 3:
for i in range(0,3):
for j in range (0,3):
if num[i] == numbers[j] and i == j:
count_strike += 1
elif num[i] == number[j] and i != j:
count_ball += 1
if count_strike == 0 and count_ball == 0:
print("3 out!")
else:
output = ""
if count_strike > 0:
output += "{} 스트라이크".format(count_strike)
if count_ball > 0:
output += "{} ".format(count_ball)

print(output.strip())
print("게임 성공")
 
실행을 시켜보면
elif num[i] == number[j] and i != j: IndexError: string index out of range
 
라고 떠서 어떻게 해야할지 뭐가 문제인지 모르겠습니다..
 
python웹-크롤링

Answer 1

0

nambaksa님의 프로필 이미지
nambaksa
Instructor

 

IndexError: string index out of range 오류는 해당 인덱스가 리스트의 범위를 벗어났다는 이야기인데 

 

for i in range(0,3):

    for j in range (0,3):

        print(num, i, j)

 

이런식으로 2중 for 문을 돌면서 num 값과 i, j 값을 출력해보며 어떤 값이 들어가있는지 어떤 경우에 오류가 발생하는지를 먼저 확인해봐야 할듯 합니다.

1019jinjune's profile image
1019jinjune

asked

Ask a question