需要使用def调用check函数twi

2024-09-26 18:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我们在做一个乱七八糟的转换器。用户输入一个选定的单词和两行乱码(每行两个字符长),将替换选定单词中的元音。你知道吗

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函数来替换这段代码,而是调用它两次。 我该怎么做呢?你知道吗


Tags: inforinputstringcheck单词entersyllable
1条回答
网友
1楼 · 发布于 2024-09-26 18:16:00
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): ")

此递归函数将验证压缩为生成器表达式,如果行无效,则使用相同的提示再次调用自身。你知道吗

相关问题 更多 >

    热门问题