我是新来的网站,到Python,所以我希望我给所有需要的信息。我已经搜索了这个问题,但没有一个解决方案似乎适用于我。返回/打印量或错误消息
我试图创建一个函数读取一些文本,然后返回它包含数字量。例如:
“这是2012”,应返回“文本有4位”
如果没有数字,它应该返回不同的消息,如:
“这是星期一”,应该返回“文本中不包含数字”
所以我写了这一点:
def CountNumbers(txt):
sum = 0
for n in txt:
if n.isdigit() == False:
print ("Text does not contain digits")
else:
sum += 1
print("Text has", sum, "digit(s)")
txt = str(input("Write some text: "))
(CountNumbers(txt))
的功能似乎是OK然而,打印出错误,例如:
Write some text: 65
Text has 2 digit(s) #this is ok, but...
当我只输入文本:
Write some text: sd
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 0 digit(s)
当我输入文本和数字(但文本在前):
Write some text: sd 564
Text does not contain digits
Text does not contain digits
Text does not contain digits
Text has 3 digit(s)
我知道我的错误在于块,(我想想),但我还没有想出办法,因为当我使用return时,它在阅读文本完成之前停止。我已经尝试了大约20多种不同的东西,请帮助我!
谢谢!
P.S.我需要这样做,作为一个.py而不只是在IDLE(Python Shell)窗口中,这就是为什么我要写这样的块。
+1简短的自我包含的代码和样本输入/输出。多个样本,甚至!爱它。 – Kevin
请记住,根据Python的命名约定,您的函数应该被命名为'count_numbers()'而不是'CountNumbers'。 – pemistahl
另外,你不应该命名一个变量'sum',因为这是一个内置函数的名字。 – abarnert