Python NameError: 名称 'now' 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15190632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:28:18  来源:igfitidea点击:

NameError: name 'now' is not defined

pythonnameerror

提问by stevengfowler

From this source code:

从这个源代码:

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)) + ".")

I am getting the following error when I run it:

当我运行它时,我收到以下错误:

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

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

采纳答案by NPE

Use raw_input()instead of input().

使用raw_input()代替input()

In Python 2, the latter tries to eval()the input, which is what's causing the exception.

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

In Python 3, there is no raw_input(); input()would work just fine (it doesn't eval()).

在 Python 3 中,没有raw_input(); input()会工作得很好(它没有eval())。

回答by Ryan Haining

use raw_input()for python2 and input()in python3. in python2, input()is the same as saying eval(raw_input())

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

if you're running this on the command line, try $python3 file.pyinstead of $python file.pyadditionally in this for i in range(len(strong)):I believe strongshould say string

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

but this code can be simplified quite a bit

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

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), ".")

replacing the '+' with ',' means you don't have to explicitly cast the return of the function to a string

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

if you'd prefer to use python2, change the bottom part to:

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

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