2012-01-10 8 views
0

의사 난수를 생성하고 사용자가 추측 할 수있는 프로그램을 작성하려고합니다. 사용자가 잘못된 숫자를 추측 할 때, 함수의 시작 부분이 아닌 조건부 루프의 시작 부분으로 돌아가고 싶습니다 (새로운 의사 난수 생성). 여기에 지금까지이 작업은 다음과 같습니다파이썬에서 숫자 추측 게임을위한 제어 루프

def guessingGame(): 
    import random 
    n = random.random() 
    input = raw_input("Guess what integer I'm thinking of.") 
    if int(input) == n: 
     print "Correct!" 
    elif int(input) < n: 
     print "Too low." 
     guessingGame() 
    elif int(input) > n: 
     print "Too high." 
     guessingGame() 
    else: 
     print "Huh?" 
     guessingGame() 

어떻게 잘못된 추측 후 번호를 변경하지 않을 수 있도록 로컬 불변의 의사 난수를 만들 수 있을까?

+4

나는 당신이 원하는 것을 할 수있는 프로그래밍 언어를 모른다. –

+3

이 질문을 '루프'라고 태그했습니다. 그래서 당신은 답이 이미 무엇인지 아는 것 같습니다 ... –

+1

BASIC을 제외하고! 승리를위한 GOTO! –

답변

1
from random import randint 

def guessingGame(): 
    n = randint(1, 10) 
    correct = False 
    while not correct: 
     raw = raw_input("Guess what integer I'm thinking of.") 
     if int(i) == n: 
      print "Correct!" 
      correct = True 
     elif int(i) < n: 
      print "Too low." 
     elif int(i) > n: 
      print "Too high." 
     else: 
      print "Huh?" 

guessingGame() 
+0

아, 잠시 루프. 감사. – sdsgg

0

여기서 가장 간단한 방법은 여기에 반복문을 사용하는 것입니다.

그러나 재귀를 사용하여 설정 한 경우 임의의 숫자를 인수로 사용하는 자체 함수에 조건부를 넣을 수 있으며 숫자를 다시 계산하지 않고 재귀 적으로 호출 할 수 있습니다.

3

여기 루핑 여기에, 아마도이 작업을 수행 할 수있는 더 좋은 방법입니다 당신은 당신의 코드에 아주 최소한의 변화 재귀를 구현 할 수있는 방법이지만 : guessingGame()에 선택적 매개 변수를 제공함으로써

def guessingGame(n=None): 
    if n is None: 
     import random 
     n = random.randint(1, 10) 
    input = raw_input("Guess what integer I'm thinking of.") 
    if int(input) == n: 
     print "Correct!" 
    elif int(input) < n: 
     print "Too low." 
     guessingGame(n) 
    elif int(input) > n: 
     print "Too high." 
     guessingGame(n) 
    else: 
     print "Huh?" 
     guessingGame(n) 

당신은 당신이 원하는 행동을 얻을 수 있습니다. 매개 변수가 제공되지 않은 경우 초기 호출이며 현재 n이 전달 된 후에 언제든지 n을 무작위로 선택해야하므로 새 값을 만들지 않습니다.

random()에 대한 호출이 으로 바뀌 었습니다. random()은 0에서 1 사이의 부동 소수점을 반환하고 코드는 예상과 정수로 나타납니다.

0

다른 방법 (일명 함수) 내에서 클래스를 만들고 논리를 정의하는 것이 최선의 방법 일 수 있습니다. Checkout the Python docs 클래스에 대한 자세한 정보.

from random import randint 

class GuessingGame (object): 

    n = randint(1,10) 

    def prompt_input(self): 
     input = raw_input("Guess what integer I'm thinking of: ") 
     self.validate_input(input) 

    def validate_input(self, input): 
     try: 
      input = int(input) 
      self.evaluate_input(input) 

     except ValueError: 
      print "Sorry, but you need to input an integer" 
      self.prompt_input() 

    def evaluate_input(self, input): 
     if input == self.n: 
      print "Correct!" 
     elif input < self.n: 
      print "Too low." 
      self.prompt_input() 
     elif input > self.n: 
      print "Too high." 
      self.prompt_input() 
     else: 
      print "Huh?" 
      self.prompt_input() 

GuessingGame().prompt_input() 
0

임의로 가져 와서 함수 외부에서 임의의 숫자를 생성 하시겠습니까? 생성 된 정수의 범위를 설정할 수도 있습니다. 예 : n = random.randint(1,max) 사용자가 최대로 미리 설정할 수도 있습니다.