如何从if语句调用用户定义的函数

2024-04-25 06:20:32 发布

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

我只是在学习Python,这是我第一次尝试学习编程语言。我已经学会了编写大多数程序(非常简单的pygLatin翻译程序(我想不出比这更蠢的东西来开始&用hehe挑战我自己)),但是我在从if语句调用函数时遇到了问题。你知道吗

以下是我所拥有的:

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()
else:
    input = ("Press any key to exit")

我希望y或y调用input_state()函数,以便能够输入另一个句子,并可以使用任何其他键退出。我提出了一个问题:

another = input("Would you like to enter another sentence to be translated? \n Y/N")

但不管按下哪个键,它仍然会结束程序,而不是重新启动程序。你知道吗


Tags: to程序younewinputifanotherbe
1条回答
网友
1楼 · 发布于 2024-04-25 06:20:32

在Python中调用函数时,程序将执行该函数,然后在调用该函数的地方继续其进程。在您的例子中,调用input_state()并不“循环”,它只调用它一次,然后转到下一行,即程序的结尾。您希望使用一个while循环,每次都检查它是否应该运行。另外,使用if another.lower() == 'y'而不是if (another == y) or (another == Y)。你知道吗

相关问题 更多 >