我们正在制作一个Gibberish转换器。用户输入一个选定的单词和两个乱码线(每两个字符长),它们将替换所选单词中的元音。
import string
print("English to Gibberish translator")
user = ""
vowels = "aeiouAEIOU"
while user.lower() != "n":
cons1 = input("Enter your first Gibberish syllable (add * for the vowel substitute): ")
check = True
while check:
for letter in cons1:
if letter not in string.ascii_letters and letter != "*":
cons1 = input("Syllable must only contain letters or a wildcard ('*'): ")
break
else:
check = False
cons2 = input("Enter the second Gibberish syllable (* for vowel substitute): ")
while check:
for letter in cons2:
if letter not in string.ascii_letters and letter != "*":
cons2 = input("Syllable must only contain letters or a wildcard ('*'): ")
break
else:
check = False
如您所见,有两个检查循环检查用户是否估算了正确的行。我们必须使用def函数来替换此代码,而是将其调用两次。 我怎么能这样做呢?
答案 0 :(得分:0)
def inputgib(pro):
val = input(pro)
valid = string.ascii_letters + ["*"]
return val if all(c in valid for c in val) else inputgib(pro)
cons1 = inputgib("Enter your first Gibberish syllable (add * for the vowel substitute): ")
cons2 = inputgib("Enter the second Gibberish syllable (* for vowel substitute): ")
这个递归函数将验证压缩到生成器表达式中,如果该行无效,则使用相同的提示再次调用自身。