简体   繁体   English

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

[英]Need help passing data from one function to another

I'm trying to pass the data from the accumulator variable "points" in the pyramid function to the statistics function. 我试图将数据从金字塔函数中的累加器变量“点”传递给统计函数。 The way I tried doing just passes the original value of "points," which is 0. Also I want statistics to receive that and run separately from the pyramid function. 我尝试执行的方法只是传递了“点”的原始值,即0。我还希望统计信息能够接收到该值并与金字塔函数分开运行。 The way it is now, the process taking place inside statistics in printing from within the pyramid function. 从现在开始,此过程在金字塔函数内部的打印统计中进行。 How can I send data from a variable from one function to another for later use when I need to call the other function? 当我需要调用另一个函数时,如何将数据从一个函数的变量发送到另一个函数,以便以后使用? The idea is that when statistics is called, it will display several pieces of information about the player--spanning across several games that will be played--like total points and the number of incorrect questions--as well as some other stuff to be implemented later. 想法是,在调用统计信息时,它将显示有关玩家的几条信息-跨过将要玩的几款游戏-例如总分和错误问题的数量-以及其他一些信息稍后实施。

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

So down below is pretty much your code provided just reworked into separate functions to remove duplicated code. 因此,下面的内容几乎就是您提供的代码,它们只是重新加工成单独的函数以删除重复的代码。

Now in the code below I have commented out lines of code and given them a number, these are the options you can ( but no limited to ) take. 现在,在下面的代码中,我注释掉了代码行,并给了它们一些数字,这些是您可以选择的(但不限于)。 Depending on which method you choose comment out the lines corresponding to the number and if you wish delete the others 根据您选择的方法,注释掉与该数字相对应的行,如果希望删除其他行

Now, option 1 implements yield this allows you to iterate over the function ask_questions and give back the current value of points. 现在,选项1实现yield,这使您可以迭代函数ask_questions并返回点的当前值。 Here you can handle the value outside the function before returning to it and continuing to ask questions. 在这里,您可以在函数外处理该值,然后再返回该函数并继续提出问题。

For option 2 this will just return the final value of points and will allow you to store it and pass it into another function 对于选项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()

I may have not understood the question entirely so here is another example which requires return ( option 2 ) 我可能还没有完全理解问题,所以这是另一个需要返回的示例(选项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)

Here in the top level function we have a list containing all the final scores the user got while running the program. 在顶层功能中,我们有一个列表,其中包含用户在运行程序时获得的所有最终分数。 You would have to change statistics to accommodate using a list instead of an int. 您将不得不更改统计信息以适应使用列表而不是int的情况。 But this way you can have multiple games while keeping the results of all the games they have played. 但是这样一来,您可以拥有多个游戏,同时保留所有已玩游戏的结果。

Well what I am trying to get at is have multiple functions to handle different things, generating, processing and displaying. 好吧,我想尝试的是具有多种功能来处理不同的事物,包括生成,处理和显示。 This way you can group it all under one top-level function that can keep track of all the data. 这样,您可以将所有内容归为一个顶级功能,该功能可以跟踪所有数据。

A quick hack(but not the suggested way to do it) to make it work would be declare the variable points global inside the function pyramid() 一个快速破解(但不是建议的实现方式)使它起作用,可以在函数pyramid()声明全局变量points

So it would become 这样就变成了

global points = 0
# and so on

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM