python函数和使用默认参数的子函数

时间:2014-03-09 08:17:10

标签: python

我正在尝试解决此分配,并在运行代码时打印额外的输出。任何人都可以告诉我在哪里弄乱了代码以及如何修复它?谢谢!我有时想要同时缩进并退回几行,我该怎么做?

分配 创建一个具有主函数和名为tester的子函数的程序。 main功能会提示用户输入input "Write something (quit ends): ",并将此input作为参数发送给子功能。

定义子功能tester,使其具有一个名为givenstring的参数,其默认值为Too short。如果用户输入少于10个字符,则程序使用默认值,如果10或更多,则打印usergiven input。如果用户输入"quit",则程序终止。如果工作正常,程序将print出类似的内容:

>>> 
Write something (quit ends): what?
Too short
Write something (quit ends): What do you mean?
What do you mean?
Write something (quit ends): Ok thats it
Ok thats it
Write something (quit ends): I am out of here
I am out of here
Write something (quit ends): quit
>>> 

测试字符串长度的最简单方法是使用函数len()。 示例输出

写一些东西(退出结束):什么? 太短 写点东西(退出结束):你是什么意思? 你什么意思? 写点东西(退出结束):好吧就是这样 好吧,就是这样 写点东西(退出结束):我不在这里 我不在这里 写点东西(退出结束):退出

我的代码:

while True: 
def tester(givenstring="Too short"):
    result=len(wrote)
    if result<10:
        print(givenstring)
    else:
        print(wrote)

wrote=input("Write something (quit ends): ")


if wrote=="quit":
    break
else:
    tester(wrote)

if __name__ == "__main__":

    tester()

我的代码输出:

Write something (quit ends): what?
what?
Too short
Write something (quit ends): What do you mean?
What do you mean?
What do you mean?
Write something (quit ends): Ok thats it
Ok thats it
Ok thats it
Write something (quit ends): I am out of here
I am out of here
I am out of here
Write something (quit ends): quit

输出应如下所示:

Write something (quit ends): what?
Too short
Write something (quit ends): What do you mean?
What do you mean?
Write something (quit ends): Ok thats it
Ok thats it
Write something (quit ends): I am out of here
I am out of here
Write something (quit ends): quit

2 个答案:

答案 0 :(得分:1)

tester只有一个参数:

def tester(givenstring="Too short"):

所以当你打电话

tester(wrote)

您将givenstring替换为wrote

更改功能定义:

def tester(wrote, givenstring="Too short"):

将函数定义移到 while循环之外也会更有效。

此外,您在没有任何参数tester的情况下致电if __name__ == "__main__"。您可以将整个while True循环包裹在def main():中并调用

def tester(...):
    ...

def main():
    while True:
        ...

if __name__ == "__main__":
    main()

答案 1 :(得分:-1)

似乎你的代码结构不起作用,并且你想使用raw_input而不是input。试试这个 -

def tester(givenstring):
    result=len(givenstring)
    if result>10:
        print(givenstring)
    else:
        print("Too short")

def main():
    while True:
        wrote=raw_input("Write something (quit ends): ")
        if wrote=="quit":
            break
        else:
            tester(wrote)

if __name__ == "__main__":
    main()