-1

我是 Python 的完整初学者,我需要一些相对简单的“帮助”(对于非初学者)。

我想做的是一个快速的“程序”,它测量输入的字符串的长度。也许我还不够努力,但我似乎无法在互联网上找到任何关于此的具体信息。

好的,这是我到目前为止所做的:

print "Please enter a number or word and I will tell you the length of it."

NR = raw_input()
print len(NR)

*NR 没有任何意义,它只是一个随机变量名

一开始一切都按预期工作。例如,我输入单词“Hello”,然后它回复“5”,或者我输入数字 100,它回复“3”,这很好,但是当我尝试输入另一个单词时,我收到此错误:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    hello
NameError: name 'hello' is not defined

但是,当我输入另一个数字(在我已经输入一个之后)时,它只会重复我输入的数字。例如,当我第一次输入数字“50”时,它会回复“2”,但当我第二次输入“50”时,它只会向我重复整数。

注意: 我想我理解第一部分的问题:它不会多次工作,因为变量“NR”仅计为已输入的第一个字符串。即使我是正确的,我仍然不知道解决这个问题。

4

1 回答 1

3

您的程序只收集一行输入,然后完成。程序完成后,您将回到用于启动程序的任何环境中。如果该环境是 python shell,那么您应该期望输入50将打印 a 50,并且输入hello将打印 no-such-variable-name 错误消息。

要让您的代码多次运行,请将其放入 while 循环中:

while True:
    print "Please enter a number or word and I will tell you the length of it."

    NR = raw_input()
    print len(NR)

注意raw_input()可以打印提示,所以不需要print语句:

while True:
    NR = raw_input("Please enter a number or word and I will tell you the length of it: ")
    print len(NR)

这个程序片段将永远运行(或者,至少在你用Control-中断它之前C)。

如果您希望能够在不中断程序的情况下停止,请尝试以下操作:

NR = None
while NR != '':
    NR = raw_input("Please enter a number or word (or a blank line to exit): ")
    print len(NR)

如果您想打印一次提示,然后用户可以输入许多字符串,请尝试以下操作:

print "Please enter a number or word and I will tell you the length of it."
while True:
    NR = raw_input()
    print len(NR)
于 2013-10-02T18:27:33.390 回答