大约两个月前,我开始学习蟒蛇,3天前我坐下来,开始写一个程序(我发现了我能做的最愚蠢和最简单的想法:一个pyglatin翻译器)。我终于让它100%起作用了。作为一个初学者,我想听到一些关于我的节目的建设性的批评;我知道我可能已经写了更多的东西,在一些事情上是需要的,在其他方面也有很长的路要走。
another_word = " "
sentence1 = " "
new_list = []
another = " "
def trans_one_word (i):
global another_word
pyg = 'ay'
original = (i)
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
another_word = new_word[1:len(new_word)]
return another_word
else:
print('empty')
def input_state():
sentence = input("enter a word to be translated: ")
list = sentence.split()
for i in list:
trans_one_word(i)
new_list.append(another_word)
s = " "
print (s.join( new_list ))
input_state()
another = input("Would you like to enter another sentence to be translated? \n Y/N")
if (another == 'y') or (another == 'Y'):
input_state()总之,我为自己在没有任何帮助的情况下写这篇文章而感到骄傲,或者除了最后的“如果”声明(我对此有一些小问题)之外,所有这些都是我的骄傲。
发布于 2016-10-30 01:12:33
关于你的代码的一些评论。总的来说,您正在使用许多不必要的变量。
another_word = " "
sentence1 = " "
new_list = []
another = " "您真的不需要在函数之外声明这些变量,它们不添加值,只会污染名称空间。
def trans_one_word (i):PEP8不推荐args之前的一个。你应该考虑有更有意义的arg名字。
global another_word不必要的全局变量,您将从函数中返回这个变量,因此不需要它是全局的
pyg = 'ay'
original = (i)家长是不必要的,您只需调用arg original,因为您不需要此作业。
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
new_word = word + first + pyg
another_word = new_word[1:len(new_word)]您不需要在一个空白的片上使用len(new_word),比如new_word[1:]。
first = word[0]
new_word = word + first + pyg
another_word = new_word[1:len(new_word)]
return another_word整个块可以简化为return word[1:] + word[0] + pyg
else:
print('empty')您不需要else:子句,因为前面的块返回了。您还应该返回原始单词。
def input_state():
sentence = input("enter a word to be translated: ")假设您想要一个给定变量名的单词或句子:
list = sentence.split()list是python类型,因此不应该用作变量名。
for i in list:
trans_one_word(i)
new_list.append(another_word)
s = " "您应该查看列表理解和生成器,因为这可以大大简化,例如print(" ".join(trans_one_word(i) for i in sentence.split()))
print (s.join( new_list ))最好返回这个结果并让调用方print它。
input_state()
another = input("Would you like to enter another sentence to be translated? \n Y/N")
if (another == 'y') or (another == 'Y'):
input_state()这个条件可以用if another in 'yY':替换,您实际上应该将所有这些都放在一个循环中,因此使用一个exit子句。
简化代码:
def trans_one_word(word):
pyg = 'ay'
if word and word.isalpha():
word = word.lower()
return word[1:] + word[0] + pyg
return word
def input_state():
sentence = input("enter a sentence to be translated: ")
return " ".join(trans_one_word(word) for word in sentence.split())
while True:
print(input_state())
another = input("Would you like to enter another sentence to be translated?\nY/N")
if another not in 'yY':
breakhttps://codereview.stackexchange.com/questions/145614
复制相似问题