如何确定应该是什么功能

时间:2016-01-27 01:09:21

标签: python function

我是编程新手,在空闲时间自学这门课程。

我现在遇到的一件事就是编写超出75行左右的程序。我无法确定何时创建一个函数来使我的程序更具可读性。我倾向于在自己的程序中迷失一点,当我看到它们时,我也觉得它们不是很“高效”。

下面是我制作的一个仍然不完整的随机文字游戏的例子。它没有完成b / c我仍然需要考虑用户可以提供无效输入的事实。现在看来会导致程序崩溃。我特别关注我的“游戏”功能,并且想知道是否有一种方法可以将其分开,或者做一些其他事情以使其更具可读性或“更好”。

以下是我的程序的代码:

#random_game
import random

def letter_guess():
    #function to prompt for and return user guess
    guess= input("Guess a letter: ").lower()
    return guess

def game(word):
    guess_count=0
    word_list=list(word)
    #formula to deternime number of guesses
    total_tries=len(word)+len(word)//2+1
    print("the word is",len(word),"characters long. "\
          "You have",total_tries,"guesses")
    template=["__" for i in range(len(word_list))]  
    print (template)

    while guess_count < total_tries and word_list != template:
        #one guess per iteration
        guess=letter_guess()                

        for i,v in enumerate(word_list):
            if guess == v:
       #adding 1 b/c I don't want a position 0.
                print("letter found at position",i+1)       
                template[i]=v
        if guess not in word_list:
            print("letter not in word.\n")
        print(template)
        guess_count+=1
    if word_list==template:
        print("you won!\n")
    else:
        print("You lose! The word was",word,"\n")

def main():
    #my initial list of words
    database=["banana","cat","superman","mississippi","sleep","volcano",\
              "school","spongebob","zebra","fish","keyboard","building",\
              "python","computer","lizard","wonderful","flower","japan"]
    while True:
        index=random.randint(0,len(database)-1)
        #get the answer to the game based on a random word selected from database
        word=database[index]
        game(word)
        again=input("would you like to play again?(yes/no) ")
        if again =="no":
            print("Thanks for playing my extremely poorly designed game!")
            break
        else:
            print("next game...\n")
main()

我可以告诉我,我的代码(特别是“游戏”功能)看起来很草率,而不是像我在其他用户发布的代码那样放在一起。

我正在努力避免不良做法,虽然我已经可以在线查找95%的问题答案,但我在这方面找不到太多材料。如果我的问题不适合本网站,也请告诉我。谢谢。

2 个答案:

答案 0 :(得分:2)

这是主观的,所以可能不完全适合SO,但我的两分钱:想象一下,你组织一群朋友来执行你的程序所做的任何任务。

您希望分割大量工作并将其分配给不同的人,以便每个人一起工作以完成工作。所以说,&#34;杰克,你做这部分。琳达,你照顾好了。维杰,你就是这么做的。&#34;

然后每个朋友成为一个职能(或随着你的经验增长,也许是一个阶级定义)。

答案 1 :(得分:2)

我相信没有规则你必须创建一个函数来使你的代码更具可读性和效率。我认为在何时/何时创建一个函数取决于偏好。

无论如何,我看看你的代码,如果你想让你的代码更简洁,(如果我是你,我会做什么)是我将创建一个处理循环部分的函数(见下文)

Api.prototype.getAccountFilterData = function (accountsList) {
    var details, rowDefaults;
    var empty = '-';
    var results = [];

    accountsList.forEach(function (account) {
        this.wrapperGetAccountFilterData(account.id, function (filtersList) {
            filtersList.forEach(function (filter) {
                rowDefaults = [
                    account.name,
                    account.id,
                    filter.name,
                    filter.id,
                    filter.type
                ];

                if (filter.type === 'EXCLUDE' || filter.type === 'INCLUDE') {
                    details = filter.getIncludeDetails() || filter.getExcludeDetails();

                    results.push(rowDefaults.concat([
                        details.field,
                        details.matchType,
                        details.expressionValue,
                        details.caseSensitive,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty
                    ]));
                }

                if (filter.type === 'UPPERCASE' || filter.type === 'LOWERCASE') {
                    details = filter.uppercaseDetails || filter.lowercaseDetails;

                    results.push(rowDefaults.concat([
                        details.field,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty
                    ]));
                }

                if (filter.type === 'SEARCH_AND_REPLACE') {
                    details = filter.searchAndReplaceDetails;

                    results.push(rowDefaults.concat([
                        details.field,
                        empty,
                        empty,
                        details.searchString,
                        details.replaceString,
                        details.caseSensitive,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty
                    ]));

                }

                if (filter.type === 'ADVANCED') {
                    details = filter.advancedDetails;

                    results.push(rowDefaults.concat([
                        details.field,
                        empty,
                        empty,
                        empty,
                        empty,
                        empty,
                        details.fieldA,
                        details.extractA,
                        details.fieldB,
                        details.extractB,
                        details.outputToField,
                        details.outputConstructor,
                        details.fieldARequired,
                        details.fieldBRequired,
                        details.overrideOutputField,
                        details.caseSensitive
                    ]));
                }
            });
        });
    }, this);

    return results;
};

希望我的建议有所帮助。

坚持下去!