파이썬 입문자 입니다 코드오류
조회수 1225회
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "AHOY! I'm the Dread Pirate Roberts, and I have a secret!"
print "It is a number from 1 to 99. I'll give you 6 tries. "
while guess != secret and tries < 6:
guess = input("what's yer guess? ")
if guess < secret:
print "Too low , ye scurvy dog!"
elif guess > secret:
print "Too high, landlubber!"
tries = tries + 1
if guess = secret:
print "Avast! Ye got it! Found my secret, ye did!"
else:
print "No more guesses! Better luck next time, matey!"
print "The secret number was", secret
헬로 파이썬 이란 책이 마음에 들어서 예제 따라하는데 자꾸 오류가 뜨네요;;;
계속 오류 빨간표시로 if guess = secret 여기서 = 가 빨간색이 나오는데
〓 책에는 이런 표시로 나와 있는데 이걸로 바꾸어도 안되고... 문제가 뭔지 잘 모르겠네요.
답변 주시면 감사하겠습니다 버전은 2.7.14 쓰는데 책은 2.7.3 써서 그런것같지는않고
답답하네요
2 답변
-
guess = input("what's yer guess? ")
여기서부터 문제가 발생했습니다..
input 함수를 통해서 무언갈 입력받으면 str(문자열) 형으로 값을 전달합니다. 이게 무슨말이냐면 아래 설명과 같습니다.
코드를 실행 시킨 뒤 화면 상에 what's yer guess?가 출력되었을 때 키보드로 값을 입력할 수 있습니다. 이 때 만약 45라는 숫자를 입력하면, guess변수에 정수 45가 입력된 게 아니라 문자열 "45"가 입력됩니다. 그렇기 때문에 guess < secret 와 같은 비교연산을 할 수 없는 것입니다. guess는 문자열이고, secret은 정수이기 때문입니다.
따라서, guess 변수에 입력 값을 정수로 변환하여 저장해주는 방법은 다음과 같습니다.
guess = int(input("what's yer guess? "))
-
(•́ ✖ •̀)
알 수 없는 사용자
-
-
책에 탈자가 있는거 같네요
if guess == secret: print "Avast! Ye got it! Found my secret, ye did!"
비교는 ==로 합니다.
헬로! 파이썬 프로그래밍 예제코드 : GitHub 링크
댓글 입력