需要帮助将数据从一个函数传递到另一个函数

时间:2016-07-02 05:34:15

标签: python python-3.x

我正在尝试将金字塔函数中累加器变量“points”的数据传递给statistics函数。我尝试的方式只是传递了“点”的原始值,即0.我还想要统计数据来接收它并与金字塔函数分开运行。现在的方式,这个过程发生在金字塔函数内的打印统计中。当我需要调用另一个函数时,如何将变量中的数据从一个函数发送到另一个函数以供以后使用?这个想法是,当调用统计数据时,它将显示有关玩家的几条信息 - 跨越几个将要玩的游戏 - 如总积分和错误问题的数量 - 以及其他一些东西。稍后实施。

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()

2 个答案:

答案 0 :(得分:1)

所以下面几乎是你提供的代码,只是重新设计成单独的函数来删除重复的代码。

现在在下面的代码中,我已经注释掉代码行并给它们一个数字,这些是您可以(但不限于)采用的选项。根据您选择的方法,注释掉与数字对应的行,如果您希望删除其他行

现在,选项1实现了yield,这允许您迭代函数ask_questions并返回当前的点值。在这里你可以在返回函数之前处理函数之外的值并继续提问。

对于选项2,这将返回点的最终值,并允许您存储它并将其传递给另一个函数

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()

我可能还没有完全理解这个问题所以这是另一个需要返回的例子(选项2)

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。但是这样你就可以拥有多个游戏,同时保持他们所有游戏的结果。

我想要的是有多个功能来处理不同的事情,生成,处理和显示。通过这种方式,您可以将其全部归入一个可以跟踪所有数据的顶级函数。

答案 1 :(得分:0)

快速入侵(但不是建议的方法)使其工作将在函数points中声明变量pyramid()全局

所以它会成为

global points = 0
# and so on