Используется ли функция main () для избавления от глобальных переменных лучше всего? - PullRequest
0 голосов
/ 11 июля 2020

Я только недавно начал изучать python. У меня были проблемы с глобальными переменными, которые мне не нужны. Ниже приведена небольшая часть моего кода, в которой показаны две переменные фраза и изображение , которые являются глобальными переменными, которые используются в моих функциях.

    # Lets the user input a phrase for the players to guess
    def choose_phrase():
        phrase = input("Type a phrase: ")

        valid_response = False
        while not valid_response:
            for character in phrase:
                valid_response = True
                if not character.isalpha() and character != ' ':
                    valid_response = False
                    phrase = input("Type a phrase with only letters and spaces: ")
                    break

        return phrase


    # This declares the ascii art in list: 'picture'. It will also add the blank letter spaces showing 
    # the players how many letters and words the phrase is. It also has a mechanism for wrapping the 
    # output for easier viewing.When wrapping, this code will produce more items in 'picture' to support 
    # more lines.
    def create_initial_picture():
        picture = [...]
        count = 1
        line = 19
        for character in phrase:
            if (character == ' ') & (count > 25):
                additional_lines = ["", "", ""]
                picture.extend(additional_lines)
                line += 3
                count = 1
            elif character == ' ':
                picture[line] = picture[line] + "    "
            else:
                picture[line] = picture[line] + "___ "
            count += 1
        return picture


    phrase = choose_phrase()
    picture = create_initial_picture()

Мне не понравилось имея глобальные переменные, поэтому я попытался эмулировать основную функцию из других языков, чтобы исправить эту проблему, и мой код выглядел так:

    def main():
        phrase = choose_phrase()
        picture = create_initial_picture(phrase)

    # Lets the user input a phrase for the players to guess
    def choose_phrase():
        phrase = input("Type a phrase: ")

        valid_response = False
        while not valid_response:
            for character in phrase:
                valid_response = True
                if not character.isalpha() and character != ' ':
                    valid_response = False
                    phrase = input("Type a phrase with only letters and spaces: ")
                    break

        return phrase


    # This declares the ascii art in list: 'picture'. It will also add the blank letter spaces showing 
    # the players how many letters and words the phrase is. It also has a mechanism for wrapping the  
    # output for easier viewing. When wrapping, this code will produce more items in 'picture' to support 
    # more lines.
    def create_initial_picture(phrase):
        picture = [...]
        count = 1
        line = 19
        for character in phrase:
            if (character == ' ') & (count > 25):
                additional_lines = ["", "", ""]
                picture.extend(additional_lines)
                line += 3
                count = 1
            elif character == ' ':
                picture[line] = picture[line] + "    "
            else:
                picture[line] = picture[line] + "___ "
            count += 1
        return picture


    main()

Это позволяет избавиться от глобальных переменных, но я не уверен если это ортодоксально или считается лучшей практикой. Я очень стараюсь выработать хорошие привычки на ранних этапах и не хочу продолжать этот метод, если он приведет меня к более серьезным проблемам в будущем. Любые отзывы об этом были бы очень полезны. Спасибо

...