我正在尝试解决此分配,并在运行代码时打印额外的输出。任何人都可以告诉我在哪里弄乱了代码以及如何修复它?谢谢!我有时想要同时缩进并退回几行,我该怎么做?
分配
创建一个具有主函数和名为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
答案 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)
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()