2012-12-17 2 views
1

방금 ​​http://learnpythonthehardway.org 다음 프로그램을 배우기 시작했습니다. 루프 및 if 문에 대해 학습 한 후 간단한 추측 게임을 만들고 싶었습니다.Python 게임 추측

잘못된 그것이 걸리면 추측 만 반복 유지 한 경우 중 하나는 CRTL의 C.에게

을 명중 할 때까지 "TOO HIGH"또는 "TOO LOW"나는 약 동안 읽고 :

문제는 루프와 다른 사람들의 코드를 읽을 수 있지만 단순히 코드를 복사하고 싶지 않아.

print ''' This is the guessing game! 
A random number will be selected from 1 to 10. 
It is your objective to guess the number!''' 

import random 

random_number = random.randrange(1, 10) 
guess = input("What could it be? > ") 
correct = False 

while not correct: 
    if guess == random_number: 
     print "CONGRATS YOU GOT IT" 
     correct = True 
    elif guess > random_number: 
     print "TOO HIGH" 
    elif guess < random_number: 
     print "TOO LOW" 
    else: 
     print "Try something else" 
+0

이 LPTHW 정말'파이썬 2 '입력()를 사용하는 사람들을 가르치고 :) 트릭을합니까? – geoffspear

+0

'while not correct :'루프에서 다시 사용자에게 프롬프트해야합니다. Eumiro의 방법이 가장 좋습니다 :). 또한, random.randrange (1, 10)은 마지막 숫자가 배타적 일 수 있으므로 1에서 9 사이의 임의의 범위를 갖습니다. 나는 그것이 확실하지 않다. 일반 오브젝트 유형에서 범위 (1, 10)는 1-9입니다. 그것은 두 번째 인수를 제외합니다. –

+0

@ F3AR3DLEGEND가 맞습니다. random.randrange (start, stop [, step])는 start <= number furins

답변

8

사용자에게 다시 질문해야합니다.

합니다 ( while 블록 내에서 그것을 유지하기 위해 네 개의 공백으로 들여 쓰기) 끝에이 줄을 추가

guess = input("What could it be? > ") 

이 그냥 빨리 해킹입니다. 그렇지 않으면 @furins가 제안한 개선 사항을 따릅니다.

3

while 루프 내부의 요청을 이동은

print ''' This is the guessing game! 
A random number will be selected from 1 to 10. 
It is your objective to guess the number!''' 

import random 

random_number = random.randrange(1, 10) 
correct = False 

while not correct: 
    guess = input("What could it be? > ") # ask as long as answer is not correct 
    if guess == random_number: 
     print "CONGRATS YOU GOT IT" 
     correct = True 
    elif guess > random_number: 
     print "TO HIGH" 
    elif guess < random_number: 
     print "TO LOW" 
    else: 
     print "Try something else" 
+0

작전은 거의 @eumiro와 거의 같은 대답입니다 ...하지만 while 루프의 시작 부분에 질문을두면 반복하지 않아도됩니다. 죄송합니다 중복 – furins

+0

및 더 나은 대답입니다. – eumiro