Python中的循环不工作

2024-05-16 01:12:56 发布

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

我很难在这里工作。我想做的是让程序跳回“请输入您要翻译的单词”一旦它运行并提供输出。你知道吗

当我在我认为合适的地方使用while truecontinue时,它只是继续打印输出。我正在翻译的单词。希望这有道理。你知道吗

下面列出的是我的工作代码。第二块是我添加while循环并遇到问题的地方。你知道吗

def silly_alpha():
    print("Looks like we're going with the Impossible alphabet.")
    word_trans = input('Please enter the word you wish to translate: ')
    if word_trans.isalpha():
        for letter in word_trans:
            print(impossible.get(letter.lower()), end=' ')
    else:
        print("There's no numbers in words. Try that again.")

这是有问题的代码

def silly_alpha():
    print("Looks like we're going with the Impossible alphabet.")
    while True:
        word_trans = input('Please enter the word you wish to translate: ')
        if word_trans.isalpha():
            for letter in word_trans:
                print(impossible.get(letter.lower()), end=' ')
                continue
        else:
            print("There's no numbers in words. Try that again.")
            continue

Tags: the代码inalphatransdef地方单词
2条回答

要让它重复循环,并接受一个新词进行翻译,只需删除那些continue语句。我在IDLE中测试了这个,效果很好。你知道吗

def silly_alpha():
    print("Looks like we're going with the Impossible alphabet.")
    while True:
        word_trans = input('Please enter the word you wish to translate: ')
        if word_trans.isalpha():
            for letter in word_trans:
                print(impossible.get(letter.lower()), end=' ')
        else:
            print("There's no numbers in words. Try that again.")

但是,现在有一个无限循环。您可能需要考虑允许用户输入终止循环的命令的某种方式。可能是这样的:

def silly_alpha():
    print("Looks like we're going with the Impossible alphabet.")
    while True:
        word_trans = input('Please enter the word you wish to translate, "x" to cancel: ')
        if word_trans == 'x':
            print('Exiting translation...')
            break
        elif word_trans.isalpha():
            for letter in word_trans:
                print(impossible.get(letter.lower()), end=' ')
        else:
            print("There's no numbers in words. Try that again.")

continue应用于最近的循环,并允许跳过此循环中的下一条指令。你知道吗

因此,您的第一条continue应用于for,因为它是循环的最后一条指令,所以没有任何效果。你知道吗

第二个continue应用于while True,因为它是循环的最后一条指令,所以没有任何效果。你知道吗

你要找的是break,它终止了最近的循环。在你的情况下,我想是while True。你知道吗

所以去掉第一个continue,用一个break替换第二个。你知道吗

相关问题 更多 >