2016-07-02 2 views
0

피라미드 함수의 accumulator 변수 "points"에서 통계 함수로 데이터를 전달하려고합니다. 내가 시도한 방식은 0 인 "points"의 원래 값을 전달합니다. 또한 통계를 받고 피라미드 함수와 별도로 실행하기를 원합니다. 지금은 피라미드 기능 내에서 인쇄 할 때 통계 내부에서 일어나는 과정입니다. 한 함수에서 다른 함수로 데이터를 전송하여 나중에 다른 함수를 호출해야 할 때 어떻게 사용할 수 있습니까? 아이디어는 통계가 호출 될 때 재생 될 여러 게임에 걸친 플레이어에 대한 몇 가지 정보 (예 : 총점 및 잘못된 질문의 수)와 기타 몇 가지 정보를 표시한다는 것입니다 나중에 구현됩니다. 이 될 것하나의 함수에서 다른 함수로 데이터를 전달하는 데 도움이 필요합니다.

import random 
from random import choice 
from random import randint 

def pyramid(): 
    for k in range (1,3): 
     print('\nPractice Problem', k, 'of 2') 
     min_pyramid_size = 3 
     max_pyramid_size = 5 
     total_chars = 0 
     num_rows = random.randint(min_pyramid_size, max_pyramid_size) 
     for i in range(num_rows): 
      x = ''.join(str(random.choice('*%')) for j in range(2*i+1)) 
      print(' ' * (num_rows - i) + x) 
      total_chars = total_chars + x.count('%') 
     try: 
      user_answer = int(input('Enter the number of % characters' + \ 
            'in the pyramid: ')) 
     except: 
       user_answer = print() 
     if user_answer == total_chars: 
      print('You are correct!') 
     else: 
      print("Sorry that's not the correct answer") 
    for k in range (1,11): 
     print('\nProblem', k, 'of 10') 
     points = 0 
     min_pyramid_size = 3 
     max_pyramid_size = 5 
     total_chars = 0 
     num_rows = random.randint(min_pyramid_size, max_pyramid_size) 
     for i in range(num_rows): 
      x = ''.join(str(random.choice('*%')) for j in range(2*i+1)) 
      print(' ' * (num_rows - i) + x) 
      total_chars = total_chars + x.count('%') 
     try: 
      user_answer = int(input('Enter the number of % characters' + \ 
            'in the pyramid: ')) 
     except: 
       user_answer = print() 
     if user_answer == total_chars: 
      print('You are correct!') 
      points +=1 
     else: 
      print("Sorry that's not the correct answer") 
    statistics(points) 




def statistics(points): 
    incorrect = 10 - (points) 
    print (points) 
    print (incorrect) 

pyramid() 
+0

'try..except' 블록의 목적이 보이지 않습니다. – TigerhawkT3

+0

잘못된 입력을 입력하면 프로그램이 충돌하지 않습니다. 그렇게하면 사용자는 아무 것도 입력 할 수 없으며 정답이 아닌 경우 잘못 표시합니다. –

답변

0

빠른 해킹이 변수 points 글로벌 기능 그래서 pyramid()

내부를 선언 할 것입니다 작동하도록 (그러나 제안 된 방법은이해야 할 일)

global points = 0 
# and so on 
1

아래 코드는 중복 된 코드를 제거하기 위해 별도의 함수로 재 작업 한 코드입니다.

아래 코드에서 코드 줄을 주석으로 처리하고 숫자를 지정하면 이러한 옵션을 사용할 수 있습니다 (그러나 이에 국한되지는 않음). 선택하는 방법에 따라 번호에 해당하는 행을 주석으로 처리하고 다른 행을 삭제하려면

이제 옵션 1은 수율을 구현합니다. 이것은 ask_questions 함수를 반복하고 점의 현재 값을 돌려 줄 수 있습니다. 여기서 함수로 돌아 가기 전에 함수 밖의 값을 처리하고 계속 질문 할 수 있습니다.

옵션이 들어이 단지 점의 최종 값을 반환하고 당신이 그것을 저장하고 나는 완전히 그래서 여기에 질문을 이해하지 수

from random import choice 
from random import randint 

def create_pyramid(): 
    min_pyramid_size = 3 
    max_pyramid_size = 5 
    num_rows = randint(min_pyramid_size, max_pyramid_size) 
    pyramid_str = '' 

    for i in range(num_rows): 
     line = ''.join(str(choice('*%')) for j in range(2*i+1)) 
     pyramid_str += ' ' * (num_rows - i) + line + '\n' 

    return pyramid_str 

def get_input(): 
    """Will keep prompting user until an int is entered""" 
    while True: 
     user_answer = input('Enter the number of % characters in the pyramid: ') 
     if user_answer.isdigit(): 
      return int(user_answer) 
     else: 
      print("Sorry, that is invalid") 

def ask_questions(text, num): 
    points = 0  
    for k in range (1, num + 1): 
     print('\n{0} {1} of {2}'.format(text, k, num)) 

     pyramid = create_pyramid() 
     print(pyramid) 

     if get_input() == pyramid.count("%"): 
      print('You are correct!') 
      points += 1 
##   yield points # 1 
     else: 
      print("Sorry that's not the correct answer") 
##   yield points # 1 

## return points # 2 

def statistics(points, total): 
    print("Score: {0} of {1}".format(points, total)) 

def main(): 
    # 1 
## for _ in ask_questions('Practice Problem', 2): 
##  pass # since we just want to ignore the points they get 
##  
## i = 1 
## for points in ask_questions('Problem', 10): 
##  statistics(points, i) 
##  i += 1 

    # 2 
## ask_questions('Practice Problem', 2) 
## points = ask_questions('Problem', 10) 
## statistics(points) # your function code for this call 

if __name__ == '__main__': 
    main() 

다른 함수로를 통과 할 수 있도록하는 또 다른 예이다

def main(): 

    print("Welcome to ... \n") 

    ask_questions('Practice Problem', 2) 
    totals = [] 
    while True: 
     totals.append(ask_questions('Problem', 10)) 
     user_input = input("Would you like to play again [Y] or [N]?") 
     if user_input.lower() != 'y': 
      break 

    statistics(points) 

최상위 함수에는 사용자가 프로그램을 실행하는 동안 얻은 최종 점수가 모두 포함 된 목록이 있습니다. int 대신 목록을 사용할 수 있도록 통계를 변경해야합니다. 하지만이 방법을 사용하면 여러 게임을 할 수 있고 게임의 모든 결과를 유지할 수 있습니다.

글쎄, 내가 얻으려고하는 것은 생성, 처리 및 표시하는 여러 가지 기능을 처리하는 여러 가지 기능이 있습니다. 이렇게하면 모든 데이터를 추적 할 수있는 하나의 최상위 함수 아래에서 모든 데이터를 그룹화 할 수 있습니다.

+0

@the_martian,이 답변으로 문제가 해결되었다고 생각되면 녹색 체크 표시를 클릭하여 '수락'으로 표시하십시오. 이것은 지역 사회가 답이없는 질문에 초점을 유지하는 데 도움이됩니다. – Lahiru

관련 문제