python - 是使用 main() 函数来摆脱全局变量的最佳实践吗?
问题描述
我最近才开始学习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()
这完成了摆脱全局变量,但我不确定这是否是正统的或被认为是最佳实践。我很想尽早养成好习惯,如果它会导致我陷入更大的问题,我不想继续这种方法。对此的任何反馈都会非常有帮助。谢谢
解决方案
推荐阅读
- ffmpeg - FFMPEG atempo 为多通道单声道音轨引入相位
- python - Docker Container is Exited with below module not found 错误
- database - 编码/数据库如何记录 sql 字符串和参数
- ios - 如何在 iOS 15 Xcode 13 中将填充图标更改为未填充 TabView tabItem?
- python - 对链接在列表中的工作方式的误解
- r - 在 R 中为常量使用整数值而不是数值(例如 1L 与 1)的好处
- python - 我需要帮助对用户在 Python 中输入的两条信息使用字符串格式
- windows - 在 Windows 上安装 Onboard.js 包的 NPM 错误
- delphi - 从 OpenToolsAPI 调用 PropertyEditor
- r - 我怎样才能让 R 系统重新组织这个小标题