【问题标题】:NameError: name 'now' is not defined [duplicate]NameError:名称“现在”未定义[重复]
【发布时间】:2013-03-03 20:44:08
【问题描述】:

从此源代码:

def numVowels(string):
    string = string.lower()
    count = 0
    for i in range(len(string)):
        if string[i] == "a" or string[i] == "e" or string[i] == "i" or \
            string[i] == "o" or string[i] == "u":
            count += 1
    return count

print ("Enter a statement: ")
strng = input()
print ("The number of vowels is: " + str(numVowels(strng)) + ".")

运行时出现以下错误:

Enter a statement:
now

Traceback (most recent call last):
  File "C:\Users\stevengfowler\exercise.py", line 11, in <module>
    strng = input()
  File "<string>", line 1, in <module>
NameError: name 'now' is not defined

==================================================

【问题讨论】:

  • for i in range(len(strong)): 不确定您是否复制/粘贴不正确或其他内容,但我很确定您的意思是 len(string)

标签: python nameerror


【解决方案1】:

使用raw_input() 代替input()

在 Python 2 中,后者尝试 eval() 输入,这就是导致异常的原因。

在 Python 3 中,没有raw_input()input() 可以正常工作(eval() 不行)。

【讨论】:

  • 谢谢!为什么它在老师的视频中起作用?我正在使用 Python 3.3。也许他用的是不同的版本?
  • @stevengfowler:如果您使用的是 Python 3,input() 可以工作。既然没有,这意味着您(无意中?)使用 Python 2。
  • 当我输入 python --version 时,我得到的是 Python 3.3.0。那么,我必须使用 3.3 吗?
  • @stevengfowler:我没有水晶球,但你的问题中的例外只能来自 Python 2.x。
  • @stevengfowler:你可能对调用哪个 python 感到困惑。将import sys 然后print(sys.version) 添加到程序的开头——这几乎肯定会显示2.something。
【解决方案2】:

在 python2 中使用 raw_input(),在 python3 中使用 input()。在python2中,input()eval(raw_input())是一样的

如果您在命令行上运行此程序,请在此for i in range(len(strong)): 中尝试使用$python3 file.py 而不是$python file.py 我相信strong 应该说string

但是这段代码可以简化很多

def num_vowels(string):
    s = s.lower()
    count = 0
    for c in s: # for each character in the string (rather than indexing)
        if c in ('a', 'e', 'i', 'o', 'u'):
            # if the character is in the set of vowels (rather than a bunch
            # of 'or's)
            count += 1
    return count

strng = input("Enter a statement:")
print("The number of vowels is:", num_vowels(strng), ".")

将 '+' 替换为 ',' 意味着您不必将函数的返回显式转换为字符串

如果您更喜欢使用python2,请将底部更改为:

strng = raw_input("Enter a statement: ")
print "The number of vowels is:", num_vowels(strng), "."

【讨论】:

    猜你喜欢
    • 2018-08-01
    • 2020-06-17
    • 2016-07-06
    • 2015-10-22
    • 2016-05-12
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    相关资源
    最近更新 更多